stuff
[oweals/gnunet.git] / src / fs / gnunet-service-fs_cp.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_cp.c
23  * @brief API to handle 'connected peers'
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-fs.h"
28 #include "gnunet-service-fs_cp.h"
29
30 /**
31  * How often do we flush trust values to disk?
32  */
33 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
34
35 /**
36  * After how long do we discard a reply?
37  */
38 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
39
40
41 /**
42  * Handle to cancel a transmission request.
43  */
44 struct GSF_PeerTransmitHandle
45 {
46
47   /**
48    * Handle for an active request for transmission to this
49    * peer, or NULL (if core queue was full).
50    */
51   struct GNUNET_CORE_TransmitHandle *cth;
52
53   /**
54    * Time when this transmission request was issued.
55    */
56   struct GNUNET_TIME_Absolute transmission_request_start_time;
57
58   /**
59    * Timeout for this request.
60    */
61   struct GNUNET_TIME_Absolute timeout;
62
63   /**
64    * Task called on timeout, or 0 for none.
65    */
66   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
67
68   /**
69    * Function to call to get the actual message.
70    */
71   GSF_GetMessageCallback gmc;
72
73   /**
74    * Peer this request targets.
75    */
76   struct GSF_ConnectedPeer *cp;
77
78   /**
79    * Closure for 'gmc'.
80    */
81   void *gmc_cls;
82
83   /**
84    * Size of the message to be transmitted.
85    */
86   size_t size;
87
88   /**
89    * GNUNET_YES if this is a query, GNUNET_NO for content.
90    */
91   int is_query;
92
93   /**
94    * Priority of this request.
95    */
96   uint32_t priority;
97
98 };
99
100
101 /**
102  * A connected peer.
103  */
104 struct GSF_ConnectedPeer 
105 {
106
107   /**
108    * Performance data for this peer.
109    */
110   struct GSF_PeerPerformanceData ppd;
111
112   /**
113    * Time until when we blocked this peer from migrating
114    * data to us.
115    */
116   struct GNUNET_TIME_Absolute last_migration_block;
117
118   /**
119    * Messages (replies, queries, content migration) we would like to
120    * send to this peer in the near future.  Sorted by priority, head.
121    */
122   struct GSF_PeerTransmitHandle *pth_head;
123
124   /**
125    * Messages (replies, queries, content migration) we would like to
126    * send to this peer in the near future.  Sorted by priority, tail.
127    */
128   struct GSF_PeerTransmitHandle *pth_tail;
129
130   /**
131    * Migration stop message in our queue, or NULL if we have none pending.
132    */
133   struct GSF_PeerTransmitHandle *migration_pth;
134
135   /**
136    * Context of our GNUNET_CORE_peer_change_preference call (or NULL).
137    * NULL if we have successfully reserved 32k, otherwise non-NULL.
138    */
139   struct GNUNET_CORE_InformationRequestContext *irc;
140
141   /**
142    * Active requests from this neighbour.
143    */
144   struct GNUNET_CONTAINER_MulitHashMap *request_map;
145
146   /**
147    * ID of delay task for scheduling transmission.
148    */
149   GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task; // FIXME: used in 'push' (ugh!)
150
151   /**
152    * Increase in traffic preference still to be submitted
153    * to the core service for this peer.
154    */
155   uint64_t inc_preference;
156
157   /**
158    * Trust rating for this peer on disk.
159    */
160   uint32_t disk_trust;
161
162   /**
163    * The peer's identity.
164    */
165   GNUNET_PEER_Id pid;
166
167   /**
168    * Which offset in "last_p2p_replies" will be updated next?
169    * (we go round-robin).
170    */
171   unsigned int last_p2p_replies_woff;
172
173   /**
174    * Which offset in "last_client_replies" will be updated next?
175    * (we go round-robin).
176    */
177   unsigned int last_client_replies_woff;
178
179   /**
180    * Current offset into 'last_request_times' ring buffer.
181    */
182   unsigned int last_request_times_off;
183
184 };
185
186
187 /**
188  * Map from peer identities to 'struct GSF_ConnectPeer' entries.
189  */
190 static struct GNUNET_CONTAINER_MultiHashMap *cp_map;
191
192
193 /**
194  * Where do we store trust information?
195  */
196 static char *trustDirectory;
197
198
199 /**
200  * Get the filename under which we would store the GNUNET_HELLO_Message
201  * for the given host and protocol.
202  * @return filename of the form DIRECTORY/HOSTID
203  */
204 static char *
205 get_trust_filename (const struct GNUNET_PeerIdentity *id)
206 {
207   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
208   char *fn;
209
210   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
211   GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
212   return fn;
213 }
214
215
216 /**
217  * Find latency information in 'atsi'.
218  *
219  * @param atsi performance data
220  * @return connection latency
221  */
222 static struct GNUNET_TIME_Relative
223 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
224 {
225   if (atsi == NULL)
226     return GNUNET_TIME_UNIT_SECONDS;
227   while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
228           (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
229     atsi++;
230   if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) 
231     {
232       GNUNET_break (0);
233       /* how can we not have latency data? */
234       return GNUNET_TIME_UNIT_SECONDS;
235     }
236   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
237                                         ntohl (atsi->value));
238 }
239
240
241 /**
242  * Update the performance information kept for the given peer.
243  *
244  * @param cp peer record to update
245  * @param atsi transport performance data
246  */
247 static void
248 update_atsi (struct GSF_ConnectedPeer *cp,
249              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
250 {
251   struct GNUNET_TIME_Relative latency;
252
253   latency = get_latency (atsi);
254   GNUNET_LOAD_value_set_decline (cp->transmission_delay,
255                                  latency);
256   /* LATER: merge atsi into cp's performance data (if we ever care...) */
257 }
258
259
260 /**
261  * Return the performance data record for the given peer
262  * 
263  * @param cp peer to query
264  * @return performance data record for the peer
265  */
266 struct GSF_PeerPerformanceData *
267 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
268 {
269   return &cp->ppd;
270 }
271
272
273 /**
274  * Core is ready to transmit to a peer, get the message.
275  *
276  * @param cls the 'struct GSF_PeerTransmitHandle' of the message
277  * @param size number of bytes core is willing to take
278  * @param buf where to copy the message
279  * @return number of bytes copied to buf
280  */
281 static size_t
282 peer_transmit_ready_cb (void *cls,
283                         size_t size,
284                         void *buf)
285 {
286   struct GSF_PeerTransmitHandle *pth = cls;
287   struct GSF_ConnectedPeer *cp;
288   size_t ret;
289
290   if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
291     {
292       GNUNET_SCHEDULER_cancel (pth->timeout_task);
293       pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
294     }
295   cp = pth->cp;
296   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
297                                cp->pth_tail,
298                                pth);
299   if (GNUNET_YES == pth->is_query)
300     {
301       cp->ppd.last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
302       GNUNET_assert (0 < cp->ppd.pending_queries--);    
303     }
304   else if (GNUNET_NO == pth->is_query)
305     {
306       GNUNET_assert (0 < cp->ppd.pending_replies--);
307     }
308   GNUNET_LOAD_update (cp->ppd.transmission_delay,
309                       GNUNET_TIME_absolute_get_duration (pth->request_start_time).rel_value);  
310   ret = pth->gmc (pth->gmc_cls, 
311                   0, NULL);
312   GNUNET_free (pth);  
313   return ret;
314 }
315
316
317 /**
318  * Function called by core upon success or failure of our bandwidth reservation request.
319  *
320  * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
321  * @param peer identifies the peer
322  * @param bandwidth_out available amount of outbound bandwidth
323  * @param amount set to the amount that was actually reserved or unreserved;
324  *               either the full requested amount or zero (no partial reservations)
325  * @param preference current traffic preference for the given peer
326  */
327 static void
328 core_reserve_callback (void *cls,
329                        const struct GNUNET_PeerIdentity * peer,
330                        struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
331                        int amount,
332                        uint64_t preference)
333 {
334   struct GSF_ConnectedPeer *cp = cls;
335   uint64_t ip;
336
337   cp->irc = NULL;
338   if (0 == amount)
339     {
340       /* failed; retry! (how did we get here!?) */
341       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
342                   _("Failed to reserve bandwidth to peer `%s'\n"),
343                   GNUNET_i2s (peer));
344       ip = cp->inc_preference;
345       cp->inc_preference = 0;
346       cp->irc = GNUNET_CORE_peer_change_preference (core,
347                                                     peer,
348                                                     GNUNET_TIME_UNIT_FOREVER_REL,
349                                                     GNUNET_BANDWIDTH_VALUE_MAX,
350                                                     GNUNET_FS_DBLOCK_SIZE,
351                                                     ip,
352                                                     &core_reserve_callback,
353                                                     cp);
354       return;
355     }
356   pth = cp->pth_head;
357   if ( (NULL != pth) &&
358        (NULL == pth->cth) )
359     {
360       /* reservation success, try transmission now! */
361       pth->cth = GNUNET_CORE_notify_transmit_ready (core,
362                                                     priority,
363                                                     GNUNET_TIME_absolute_get_remaining (pth->timeout),
364                                                     &target,
365                                                     size,
366                                                     &peer_transmit_ready_cb,
367                                                     pth);
368     }
369 }
370
371
372 /**
373  * A peer connected to us.  Setup the connected peer
374  * records.
375  *
376  * @param peer identity of peer that connected
377  * @param atsi performance data for the connection
378  * @return handle to connected peer entry
379  */
380 struct GSF_ConnectedPeer *
381 GSF_peer_connect_handler_ (const struct GNUNET_PeerIdentity *peer,
382                            const struct GNUNET_TRANSPORT_ATS_Information *atsi)
383 {
384   struct GSF_ConnectedPeer *cp;
385   char *fn;
386   uint32_t trust;
387   struct GNUNET_TIME_Relative latency;
388
389   cp = GNUNET_malloc (sizeof (struct GSF_ConnectedPeer));
390   cp->transmission_delay = GNUNET_LOAD_value_init (latency);
391   cp->pid = GNUNET_PEER_intern (peer);
392   cp->transmission_delay = GNUNET_LOAD_value_init (0);
393   cp->irc = GNUNET_CORE_peer_change_preference (core,
394                                                 peer,
395                                                 GNUNET_TIME_UNIT_FOREVER_REL,
396                                                 GNUNET_BANDWIDTH_VALUE_MAX,
397                                                 GNUNET_FS_DBLOCK_SIZE,
398                                                 0,
399                                                 &core_reserve_callback,
400                                                 cp);
401   fn = get_trust_filename (peer);
402   if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
403       (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
404     cp->disk_trust = cp->trust = ntohl (trust);
405   GNUNET_free (fn);
406   cp->request_map = GNUNET_CONTAINER_multihashmap_create (128);
407   GNUNET_break (GNUNET_OK ==
408                 GNUNET_CONTAINER_multihashmap_put (cp_map,
409                                                    &peer->hashPubKey,
410                                                    cp,
411                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
412   update_atsi (cp, atsi);
413   GSF_plan_notify_new_peer_ (cp);
414   return cp;
415 }
416
417
418 /**
419  * Handle P2P "MIGRATION_STOP" message.
420  *
421  * @param cls closure, always NULL
422  * @param other the other peer involved (sender or receiver, NULL
423  *        for loopback messages where we are both sender and receiver)
424  * @param message the actual message
425  * @param atsi performance information
426  * @return GNUNET_OK to keep the connection open,
427  *         GNUNET_SYSERR to close it (signal serious error)
428  */
429 int
430 GSF_handle_p2p_migration_stop_ (void *cls,
431                                 const struct GNUNET_PeerIdentity *other,
432                                 const struct GNUNET_MessageHeader *message,
433                                 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
434 {
435   struct GSF_ConnectedPeer *cp; 
436   const struct MigrationStopMessage *msm;
437
438   msm = (const struct MigrationStopMessage*) message;
439   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
440                                           &other->hashPubKey);
441   if (cp == NULL)
442     {
443       GNUNET_break (0);
444       return GNUNET_OK;
445     }
446   cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
447   update_atsi (cp, atsi);
448   return GNUNET_OK;
449 }
450
451
452 /**
453  * Copy reply and free put message.
454  *
455  * @param cls the 'struct PutMessage'
456  * @param buf_size number of bytes available in buf
457  * @param buf where to copy the message, NULL on error (peer disconnect)
458  * @return number of bytes copied to 'buf', can be 0 (without indicating an error)
459  */
460 static size_t 
461 copy_reply (void *cls,
462             size_t buf_size,
463             void *buf)
464 {
465   struct PutMessage *pm = cls;
466
467   if (buf != NULL)
468     {
469       GNUNET_assert (size >= ntohs (pm->header.size));
470       size = ntohs (pm->header.size);
471       memcpy (buf, pm, size); 
472       GNUNET_STATISTICS_update (stats,
473                                 gettext_noop ("# replies transmitted to other peers"),
474                                 1,
475                                 GNUNET_NO); 
476     }
477   else
478     {
479       GNUNET_STATISTICS_update (stats,
480                                 gettext_noop ("# replies dropped"),
481                                 1,
482                                 GNUNET_NO); 
483     }
484   GNUNET_free (pm);
485   return size;
486 }
487
488
489 /**
490  * Handle a reply to a pending request.  Also called if a request
491  * expires (then with data == NULL).  The handler may be called
492  * many times (depending on the request type), but will not be
493  * called during or after a call to GSF_pending_request_cancel 
494  * and will also not be called anymore after a call signalling
495  * expiration.
496  *
497  * @param cls 'struct GSF_ConnectedPeer' of the peer that would
498  *            have liked an answer to the request
499  * @param pr handle to the original pending request
500  * @param expiration when does 'data' expire?
501  * @param data response data, NULL on request expiration
502  * @param data_len number of bytes in data
503  * @param more GNUNET_YES if the request remains active (may call
504  *             this function again), GNUNET_NO if the request is
505  *             finished (client must not call GSF_pending_request_cancel_)
506  */
507 static void
508 handle_p2p_reply (void *cls,
509                   struct GSF_PendingRequest *pr,
510                   struct GNUNET_TIME_Absolute expiration,
511                   const void *data,
512                   size_t data_len,
513                   int more)
514 {
515   struct GSF_ConnectedPeer *cp = cls;
516   struct GSF_PendingRequest *prd;
517   struct PutMessage *pm;
518   size_t msize;
519
520   prd = GSF_pending_request_get_data_ (pr);
521   if (NULL == data)
522     {
523       GNUNET_assert (GNUNET_NO == more);
524       GNUNET_STATISTICS_update (stats,
525                                 gettext_noop ("# P2P searches active"),
526                                 -1,
527                                 GNUNET_NO);
528       GNUNET_break (GNUNET_OK ==
529                     GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
530                                                           &prd->query,
531                                                           pr));
532       return;
533     }
534 #if DEBUG_FS
535   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
536               "Transmitting result for query `%s'\n",
537               GNUNET_h2s (key));
538 #endif  
539   GNUNET_STATISTICS_update (stats,
540                             gettext_noop ("# replies received for other peers"),
541                             1,
542                             GNUNET_NO); 
543   msize = sizeof (struct PutMessage) + data_len;
544   pm = GNUNET_malloc (sizeof (msize));
545   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
546   pm->header.size = htons (msize);
547   pm->type = htonl (prd->type);
548   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
549   memcpy (&pm[1], data, data_len);
550   (void) GSF_peer_transmit_ (cp, GNUNET_NO,
551                              UINT32_MAX,
552                              REPLY_TIMEOUT,
553                              msize,
554                              &copy_reply,
555                              pm);
556 }
557
558
559 /**
560  * Handle P2P "QUERY" message.  Creates the pending request entry
561  * and sets up all of the data structures to that we will
562  * process replies properly.  Does not initiate forwarding or
563  * local database lookups.
564  *
565  * @param other the other peer involved (sender or receiver, NULL
566  *        for loopback messages where we are both sender and receiver)
567  * @param message the actual message
568  * @return pending request handle, NULL on error
569  */
570 struct GSF_PendingRequest *
571 GSF_handle_p2p_query_ (const struct GNUNET_PeerIdentity *other,
572                        const struct GNUNET_MessageHeader *message)
573 {
574   struct GSF_PendingRequest *pr;
575   struct GSF_PendingRequestData *prd;
576   struct GSF_ConnectedPeer *cp;
577   struct GSF_ConnectedPeer *cps;
578   GNUNET_HashCode *namespace;
579   struct GNUNET_PeerIdentity *target;
580   enum GSF_PendingRequestOptions options;                            
581   struct GNUNET_TIME_Relative timeout;
582   uint16_t msize;
583   const struct GetMessage *gm;
584   unsigned int bits;
585   const GNUNET_HashCode *opt;
586   uint32_t bm;
587   size_t bfsize;
588   uint32_t ttl_decrement;
589   int32_t priority;
590   int32_t ttl;
591   enum GNUNET_BLOCK_Type type;
592
593
594   msize = ntohs(message->size);
595   if (msize < sizeof (struct GetMessage))
596     {
597       GNUNET_break_op (0);
598       return GNUNET_SYSERR;
599     }
600   gm = (const struct GetMessage*) message;
601 #if DEBUG_FS
602   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
603               "Received request for `%s'\n",
604               GNUNET_h2s (&gm->query));
605 #endif
606   type = ntohl (gm->type);
607   bm = ntohl (gm->hash_bitmap);
608   bits = 0;
609   while (bm > 0)
610     {
611       if (1 == (bm & 1))
612         bits++;
613       bm >>= 1;
614     }
615   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
616     {
617       GNUNET_break_op (0);
618       return GNUNET_SYSERR;
619     }  
620   opt = (const GNUNET_HashCode*) &gm[1];
621   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
622   /* bfsize must be power of 2, check! */
623   if (0 != ( (bfsize - 1) & bfsize))
624     {
625       GNUNET_break_op (0);
626       return GNUNET_SYSERR;
627     }
628   cover_query_count++;
629   bm = ntohl (gm->hash_bitmap);
630   bits = 0;
631   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
632                                            &other->hashPubKey);
633   if (NULL == cps)
634     {
635       /* peer must have just disconnected */
636       GNUNET_STATISTICS_update (stats,
637                                 gettext_noop ("# requests dropped due to initiator not being connected"),
638                                 1,
639                                 GNUNET_NO);
640       return GNUNET_SYSERR;
641     }
642   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
643     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
644                                             &opt[bits++]);
645   else
646     cp = cps;
647   if (cp == NULL)
648     {
649 #if DEBUG_FS
650       if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
651         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
652                     "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
653                     GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
654       
655       else
656         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
657                     "Failed to find peer `%4s' in connection set. Dropping query.\n",
658                     GNUNET_i2s (other));
659 #endif
660       GNUNET_STATISTICS_update (stats,
661                                 gettext_noop ("# requests dropped due to missing reverse route"),
662                                 1,
663                                 GNUNET_NO);
664       return GNUNET_OK;
665     }
666   /* note that we can really only check load here since otherwise
667      peers could find out that we are overloaded by not being
668      disconnected after sending us a malformed query... */
669   priority = bound_priority (ntohl (gm->priority), cps);
670   if (priority < 0)
671     {
672 #if DEBUG_FS
673       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
674                   "Dropping query from `%s', this peer is too busy.\n",
675                   GNUNET_i2s (other));
676 #endif
677       return GNUNET_OK;
678     }
679 #if DEBUG_FS 
680   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
682               GNUNET_h2s (&gm->query),
683               (unsigned int) type,
684               GNUNET_i2s (other),
685               (unsigned int) bm);
686 #endif
687   namespace = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) ? &opt[bits++] : NULL;
688   target = (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? ((const struct GNUNET_PeerIdentity*) &opt[bits++]) : NULL;
689   options = 0;
690   if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
691        (GNUNET_LOAD_get_average (cp->transmission_delay) > 
692         GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
693     {
694       /* don't have BW to send to peer, or would likely take longer than we have for it,
695          so at best indirect the query */
696       priority = 0;
697       options |= GSF_PRO_FORWARD_ONLY;
698     }
699   ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
700   /* decrement ttl (always) */
701   ttl_decrement = 2 * TTL_DECREMENT +
702     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
703                               TTL_DECREMENT);
704   if ( (ttl < 0) &&
705        (((int32_t)(ttl - ttl_decrement)) > 0) )
706     {
707 #if DEBUG_FS
708       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
709                   "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
710                   GNUNET_i2s (other),
711                   ttl,
712                   ttl_decrement);
713 #endif
714       GNUNET_STATISTICS_update (stats,
715                                 gettext_noop ("# requests dropped due TTL underflow"),
716                                 1,
717                                 GNUNET_NO);
718       /* integer underflow => drop (should be very rare)! */      
719       return GNUNET_OK;
720     } 
721   ttl -= ttl_decrement;
722
723   /* test if the request already exists */
724   pr = GNUNET_CONTAINER_multihashmap_get (cp->request_map,
725                                           &gm->query);
726   if (pr != NULL) 
727     {      
728       prd = GSF_pending_request_get_data_ (pr);
729       if ( (prd->type == type) &&
730            ( (type != GNUNET_BLOCK_TYPE_SBLOCK) ||
731              (0 == memcmp (prd->namespace,
732                            namespace,
733                            sizeof (GNUNET_HashCode))) ) )
734         {
735           if (prd->ttl.abs_value >= GNUNET_TIME_absolute_get().abs_value + ttl)
736             {
737               /* existing request has higher TTL, drop new one! */
738               prd->priority += priority;
739 #if DEBUG_FS
740               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
741                           "Have existing request with higher TTL, dropping new request.\n",
742                           GNUNET_i2s (other));
743 #endif
744               GNUNET_STATISTICS_update (stats,
745                                         gettext_noop ("# requests dropped due to higher-TTL request"),
746                                         1,
747                                         GNUNET_NO);
748               return GNUNET_OK;
749             }
750           /* existing request has lower TTL, drop old one! */
751           pr->priority += prd->priority;
752           GSF_pending_request_cancel_ (pr);
753           GNUNET_assert (GNUNET_YES ==
754                          GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
755                                                                &gm->query,
756                                                                pr));
757         }
758     }
759   
760   pr = GSF_pending_request_create (options,
761                                    type,
762                                    &gm->query,
763                                    namespace,
764                                    target,
765                                    (bf_size > 0) ? (const char*)&opt[bits] : NULL,
766                                    bf_size,
767                                    ntohl (gm->filter_mutator),
768                                    1 /* anonymity */
769                                    (uint32_t) priority,
770                                    ttl,
771                                    NULL, 0, /* replies_seen */
772                                    &handle_p2p_reply,
773                                    cp);
774   GNUNET_break (GNUNET_OK ==
775                 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
776                                                    &gm->query,
777                                                    pr,
778                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
779   GNUNET_STATISTICS_update (stats,
780                             gettext_noop ("# P2P searches received"),
781                             1,
782                             GNUNET_NO);
783   GNUNET_STATISTICS_update (stats,
784                             gettext_noop ("# P2P searches active"),
785                             1,
786                             GNUNET_NO);
787   return pr;
788 }
789
790
791 /**
792  * Function called if there has been a timeout trying to satisfy
793  * a transmission request.
794  *
795  * @param cls the 'struct GSF_PeerTransmitHandle' of the request 
796  * @param tc scheduler context
797  */
798 static void
799 peer_transmit_timeout (void *cls,
800                        const struct GNUNET_SCHEDULER_TaskContext *tc)
801 {
802   struct GSF_PeerTransmitHandle *pth = cls;
803   struct GSF_ConnectedPeer *cp;
804   
805   pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
806   cp = pth->cp;
807   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
808                                cp->pth_tail,
809                                pth);
810   if (GNUNET_YES == pth->is_query)
811     GNUNET_assert (0 < cp->ppd.pending_queries--);    
812   else if (GNUNET_NO == pth->is_query)
813     GNUNET_assert (0 < cp->ppd.pending_replies--);
814   GNUNET_LOAD_update (cp->ppd.transmission_delay,
815                       UINT64_MAX);
816   pth->gmc (pth->gmc_cls, 
817             0, NULL);
818   GNUNET_free (pth);
819 }
820
821
822 /**
823  * Transmit a message to the given peer as soon as possible.
824  * If the peer disconnects before the transmission can happen,
825  * the callback is invoked with a 'NULL' buffer.
826  *
827  * @param peer target peer
828  * @param is_query is this a query (GNUNET_YES) or content (GNUNET_NO) or neither (GNUNET_SYSERR)
829  * @param priority how important is this request?
830  * @param timeout when does this request timeout (call gmc with error)
831  * @param size number of bytes we would like to send to the peer
832  * @param gmc function to call to get the message
833  * @param gmc_cls closure for gmc
834  * @return handle to cancel request
835  */
836 struct GSF_PeerTransmitHandle *
837 GSF_peer_transmit_ (struct GSF_ConnectedPeer *peer,
838                     int is_query,
839                     uint32_t priority,
840                     struct GNUNET_TIME_Relative timeout,
841                     size_t size,
842                     GSF_GetMessageCallback gmc,
843                     void *gmc_cls)
844 {
845   struct GSF_ConnectedPeer *cp;
846   struct GSF_PeerTransmitHandle *pth;
847   struct GSF_PeerTransmitHandle *pos;
848   struct GSF_PeerTransmitHandle *prev;
849   struct GNUNET_PeerIdentity target;
850   uint64_t ip;
851   int is_ready;
852
853   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
854                                           &peer->hashPubKey);
855   GNUNET_assert (NULL != cp);
856   pth = GNUNET_malloc (sizeof (struct GSF_PeerTransmitHandle));
857   pth->transmission_request_start_time = GNUNET_TIME_absolute_now ();
858   pth->timeout = GNUNET_TIME_relative_to_absolute (timeout);
859   pth->gmc = gmc;
860   pth->gmc_cls = gmc_cls;
861   pth->size = size;
862   pth->is_query = is_query;
863   pth->priority = priority;
864   pth->cp = cp;
865   /* insertion sort (by priority, descending) */
866   prev = NULL;
867   pos = cp->pth_head;
868   while ( (pos != NULL) &&
869           (pos->priority > priority) )
870     {
871       prev = pos;
872       pos = pos->next;
873     }
874   if (prev == NULL)
875     GNUNET_CONTAINER_DLL_insert_head (cp->pth_head,
876                                       cp->pth_tail,
877                                       pth);
878   else
879     GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
880                                        cp->pth_tail,
881                                        prev,
882                                        pth);
883   GNUNET_PEER_resolve (cp->pid,
884                        &target);
885   if (GNUNET_YES == is_query)
886     {
887       /* query, need reservation */
888       cp->ppd.pending_queries++;
889       if (NULL == cp->irc)
890         {
891           /* reservation already done! */
892           is_ready = GNUNET_YES;
893           ip = cp->inc_preference;
894           cp->inc_preference = 0;
895           cp->irc = GNUNET_CORE_peer_change_preference (core,
896                                                         peer,
897                                                         GNUNET_TIME_UNIT_FOREVER_REL,
898                                                         GNUNET_BANDWIDTH_VALUE_MAX,
899                                                         GNUNET_FS_DBLOCK_SIZE,
900                                                         ip,
901                                                         &core_reserve_callback,
902                                                         cp);      
903         }
904       else
905         {
906           /* still waiting for reservation */
907           is_ready = GNUNET_NO;
908         }
909     }
910   else if (GNUNET_NO == is_query)
911     {
912       /* no reservation needed for content */
913       cp->ppd.pending_replies++;
914       is_ready = GNUNET_YES;
915     }
916   else
917     {
918       /* not a query or content, no reservation needed */
919       is_ready = GNUNET_YES;
920     }
921   if (is_ready)
922     {
923       pth->cth = GNUNET_CORE_notify_transmit_ready (core,
924                                                     priority,
925                                                     timeout,
926                                                     &target,
927                                                     size,
928                                                     &peer_transmit_ready_cb,
929                                                     pth);
930       /* pth->cth could be NULL here, that's OK, we'll try again
931          later... */
932     }
933   if (pth->cth == NULL)
934     {
935       /* if we're waiting for reservation OR if we could not do notify_transmit_ready,
936          install a timeout task to be on the safe side */
937       pth->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
938                                                         &peer_transmit_timeout,
939                                                         pth);
940     }
941   return pth;
942 }
943
944
945 /**
946  * Cancel an earlier request for transmission.
947  *
948  * @param pth request to cancel
949  */
950 void
951 GSF_peer_transmit_cancel_ (struct GSF_PeerTransmitHandle *pth)
952 {
953   struct GSF_PeerTransmitHandle *pth = cls;
954   struct GSF_ConnectedPeer *cp;
955
956   if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
957     {
958       GNUNET_SCHEDULER_cancel (pth->timeout_task);
959       pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
960     }
961   if (NULL != pth->cth)
962     {
963       GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
964       pth->cth = NULL;
965     }
966   cp = pth->cp;
967   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
968                                cp->pth_tail,
969                                pth);
970   if (GNUNET_YES == pth->is_query)
971     GNUNET_assert (0 < cp->ppd.pending_queries--);    
972   else if (GNUNET_NO == pth->is_query)
973     GNUNET_assert (0 < cp->ppd.pending_replies--);
974   GNUNET_free (pth);
975 }
976
977
978 /**
979  * Report on receiving a reply; update the performance record of the given peer.
980  *
981  * @param cp responding peer (will be updated)
982  * @param request_time time at which the original query was transmitted
983  * @param request_priority priority of the original request
984  * @param initiator_client local client on responsible for query (or NULL)
985  * @param initiator_peer other peer responsible for query (or NULL)
986  */
987 void
988 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
989                               struct GNUNET_TIME_Absolute request_time,
990                               uint32_t request_priority,
991                               const struct GSF_LocalClient *initiator_client,
992                               const struct GSF_ConnectedPeer *initiator_peer)
993 {
994   struct GNUNET_TIME_Relative delay;
995   unsigned int i;
996
997   delay = GNUNET_TIME_absolute_get_duration (request_time);  
998   cp->ppd.avg_reply_delay = (cp->ppd.avg_reply_delay * (RUNAVG_DELAY_N-1) + delay.rel_value) / RUNAVG_DELAY_N;
999   cp->ppd.avg_priority = (cp->avg_priority * (RUNAVG_DELAY_N-1) + request_priority) / RUNAVG_DELAY_N;
1000   if (NULL != initiator_client)
1001     {
1002       cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1003     }
1004   else if (NULL != initiator_peer)
1005     {
1006       GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
1007       cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff++ % P2P_SUCCESS_LIST_SIZE] = initiator_peer->pid;
1008       GNUNET_PEER_change_rc (initiator_peer->pid, 1);
1009     }
1010   else
1011     GNUNET_break (0);
1012 }
1013
1014
1015 /**
1016  * Method called whenever a given peer has a status change.
1017  *
1018  * @param cls closure
1019  * @param peer peer identity this notification is about
1020  * @param bandwidth_in available amount of inbound bandwidth
1021  * @param bandwidth_out available amount of outbound bandwidth
1022  * @param timeout absolute time when this peer will time out
1023  *        unless we see some further activity from it
1024  * @param atsi status information
1025  */
1026 void
1027 GSF_peer_status_handler_ (void *cls,
1028                           const struct GNUNET_PeerIdentity *peer,
1029                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1030                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1031                           struct GNUNET_TIME_Absolute timeout,
1032                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1033 {
1034   struct GSF_ConnectedPeer *cp;
1035
1036   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1037                                           &peer->hashPubKey);
1038   GNUNET_assert (NULL != cp);
1039   update_atsi (cp, atsi);
1040 }
1041
1042
1043 /**
1044  * Cancel all requests associated with the peer.
1045  *
1046  * @param cls unused
1047  * @param query hash code of the request
1048  * @param value the 'struct GSF_PendingRequest'
1049  * @return GNUNET_YES (continue to iterate)
1050  */
1051 static int
1052 cancel_pending_request (void *cls,
1053                         const GNUNET_HashCode *query,
1054                         void *value)
1055 {
1056   struct GSF_PendingRequest *pr = value;
1057
1058   GSF_pending_request_cancel_ (pr);
1059   return GNUNET_OK;
1060 }
1061
1062
1063 /**
1064  * A peer disconnected from us.  Tear down the connected peer
1065  * record.
1066  *
1067  * @param cls unused
1068  * @param peer identity of peer that connected
1069  */
1070 void
1071 GSF_peer_disconnect_handler_ (void *cls,
1072                               const struct GNUNET_PeerIdentity *peer)
1073 {
1074   struct GSF_ConnectedPeer *cp;
1075   struct GSF_PeerTransmitHandle *pth;
1076
1077   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1078                                           &peer->hashPubKey);
1079   GNUNET_assert (NULL != cp);
1080   GNUNET_CONTAINER_multihashmap_remove (cp_map,
1081                                         &peer->hashPubKey,
1082                                         cp);
1083   if (NULL != cp->migration_pth)
1084     {
1085       GSF_peer_transmit_cancel_ (cp->migration_pth);
1086       cp->migration_pth = NULL;
1087     }
1088   if (NULL != cp->irc)
1089     {
1090       GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1091       cp->irc = NULL;
1092     }
1093   GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1094                                          &cancel_pending_request,
1095                                          cp);
1096   GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1097   cp->request_map = NULL;
1098   GSF_plan_notify_peer_disconnect_ (cp);
1099   GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1100   GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1101   while (NULL != (pth = cp->pth_head))
1102     {
1103       if (NULL != pth->th)
1104         {
1105           GNUNET_CORE_notify_transmit_ready_cancel (pth->th);
1106           pth->th = NULL;
1107         }
1108       GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1109                                    cp->pth_tail,
1110                                    pth);
1111       GNUNET_free (pth);
1112     }
1113   GNUNET_PEER_change_rc (cp->pid, -1);
1114   GNUNET_free (cp);
1115 }
1116
1117
1118 /**
1119  * Closure for 'call_iterator'.
1120  */
1121 struct IterationContext
1122 {
1123   /**
1124    * Function to call on each entry.
1125    */
1126   GSF_ConnectedPeerIterator it;
1127
1128   /**
1129    * Closure for 'it'.
1130    */
1131   void *it_cls;
1132 };
1133
1134
1135 /**
1136  * Function that calls the callback for each peer.
1137  *
1138  * @param cls the 'struct IterationContext*'
1139  * @param key identity of the peer
1140  * @param value the 'struct GSF_ConnectedPeer*'
1141  * @return GNUNET_YES to continue iteration
1142  */
1143 static int
1144 call_iterator (void *cls,
1145                const GNUNET_HashCode *key,
1146                void *value)
1147 {
1148   struct IterationContext *ic = cls;
1149   struct GSF_ConnectedPeer *cp = value;
1150   
1151   ic->it (ic->it_cls,
1152           (const struct GNUNET_PeerIdentity*) key,
1153           cp,
1154           &cp->ppd);
1155   return GNUNET_YES;
1156 }
1157
1158
1159 /**
1160  * Iterate over all connected peers.
1161  *
1162  * @param it function to call for each peer
1163  * @param it_cls closure for it
1164  */
1165 void
1166 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1167                               void *it_cls)
1168 {
1169   struct IterationContext ic;
1170
1171   ic.it = it;
1172   ic.it_cls = it_cls;
1173   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1174                                          &call_iterator,
1175                                          &ic);
1176 }
1177
1178
1179 /**
1180  * Obtain the identity of a connected peer.
1181  *
1182  * @param cp peer to reserve bandwidth from
1183  * @param id identity to set (written to)
1184  */
1185 void
1186 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1187                                   struct GNUNET_PeerIdentity *id)
1188 {
1189   GNUNET_PEER_resolve (cp->pid,
1190                        &id);
1191 }
1192
1193
1194 /**
1195  * Assemble a migration stop message for transmission.
1196  *
1197  * @param cls the 'struct GSF_ConnectedPeer' to use
1198  * @param size number of bytes we're allowed to write to buf
1199  * @param buf where to copy the message
1200  * @return number of bytes copied to buf
1201  */
1202 static size_t
1203 create_migration_stop_message (void *cls,
1204                                size_t size,
1205                                void *buf)
1206 {
1207   struct GSF_ConnectedPeer *cp = cls;
1208   struct MigrationStopMessage msm;
1209
1210   cp->migration_pth = NULL;
1211   if (NULL == buf)
1212     return 0;
1213   GNUNET_assert (size > sizeof (struct MigrationStopMessage));
1214   msm.header.size = htons (sizeof (struct MigrationStopMessage));
1215   msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1216   msm.duration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block));
1217   memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1218   return sizeof (struct MigrationStopMessage);
1219 }
1220
1221
1222 /**
1223  * Ask a peer to stop migrating data to us until the given point
1224  * in time.
1225  * 
1226  * @param cp peer to ask
1227  * @param block_time until when to block
1228  */
1229 void
1230 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1231                            struct GNUNET_TIME_Relative block_time)
1232 {
1233   if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value > block_time.rel_value)
1234     return; /* already blocked */
1235   cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
1236   if (cp->migration_pth != NULL)
1237     GSF_peer_transmit_cancel_ (cp->migration_pth);
1238   cp->migration_pth 
1239     = GSF_peer_transmit_ (cp,
1240                           GNUNET_SYSERR,
1241                           UINT32_MAX,
1242                           GNUNET_TIME_UNIT_FOREVER_REL,
1243                           sizeof (struct MigrationStopMessage),
1244                           &create_migration_stop_message,
1245                           cp);
1246 }
1247
1248
1249 /**
1250  * Write host-trust information to a file - flush the buffer entry!
1251  *
1252  * @param cls closure, not used
1253  * @param key host identity
1254  * @param value the 'struct GSF_ConnectedPeer' to flush
1255  * @return GNUNET_OK to continue iteration
1256  */
1257 static int
1258 flush_trust (void *cls,
1259              const GNUNET_HashCode *key,
1260              void *value)
1261 {
1262   struct GSF_ConnectedPeer *cp = value;
1263   char *fn;
1264   uint32_t trust;
1265   struct GNUNET_PeerIdentity pid;
1266
1267   if (cp->trust == cp->disk_trust)
1268     return GNUNET_OK;                     /* unchanged */
1269   GNUNET_PEER_resolve (cp->pid,
1270                        &pid);
1271   fn = get_trust_filename (&pid);
1272   if (cp->trust == 0)
1273     {
1274       if ((0 != UNLINK (fn)) && (errno != ENOENT))
1275         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1276                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1277     }
1278   else
1279     {
1280       trust = htonl (cp->trust);
1281       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
1282                                                     sizeof(uint32_t),
1283                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1284                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1285         cp->disk_trust = cp->trust;
1286     }
1287   GNUNET_free (fn);
1288   return GNUNET_OK;
1289 }
1290
1291
1292 /**
1293  * Notify core about a preference we have for the given peer
1294  * (to allocate more resources towards it).  The change will
1295  * be communicated the next time we reserve bandwidth with
1296  * core (not instantly).
1297  *
1298  * @param cp peer to reserve bandwidth from
1299  * @param pref preference change
1300  */
1301 void
1302 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1303                                        uint64_t pref)
1304 {
1305   cp->inc_preference += pref;
1306 }
1307
1308
1309 /**
1310  * Call this method periodically to flush trust information to disk.
1311  *
1312  * @param cls closure, not used
1313  * @param tc task context, not used
1314  */
1315 static void
1316 cron_flush_trust (void *cls,
1317                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1318 {
1319
1320   if (NULL == cp_map)
1321     return;
1322   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1323                                          &flush_trust,
1324                                          NULL);
1325   if (NULL == tc)
1326     return;
1327   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1328     return;
1329   GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, 
1330                                 &cron_flush_trust, 
1331                                 NULL);
1332 }
1333
1334
1335 /**
1336  * Initialize peer management subsystem.
1337  *
1338  * @param cfg configuration to use
1339  */
1340 void
1341 GSF_connected_peer_init_ (struct GNUNET_CONFIGURATION_Handle *cfg)
1342 {
1343   cp_map = GNUNET_CONTAINER_multihashmap_create (128);
1344   GNUNET_assert (GNUNET_OK ==
1345                  GNUNET_CONFIGURATION_get_value_filename (cfg,
1346                                                           "fs",
1347                                                           "TRUST",
1348                                                           &trustDirectory));
1349   GNUNET_DISK_directory_create (trustDirectory);
1350   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1351                                       &cron_flush_trust, NULL);
1352 }
1353
1354
1355 /**
1356  * Iterator to free peer entries.
1357  *
1358  * @param cls closure, unused
1359  * @param key current key code
1360  * @param value value in the hash map (peer entry)
1361  * @return GNUNET_YES (we should continue to iterate)
1362  */
1363 static int 
1364 clean_peer (void *cls,
1365             const GNUNET_HashCode * key,
1366             void *value)
1367 {
1368   GSF_peer_disconnect_handler_ (NULL, 
1369                                 (const struct GNUNET_PeerIdentity*) key);
1370   return GNUNET_YES;
1371 }
1372
1373
1374 /**
1375  * Shutdown peer management subsystem.
1376  */
1377 void
1378 GSF_connected_peer_done_ ()
1379 {
1380   cron_flush_trust (NULL, NULL);
1381   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1382                                          &clean_peer,
1383                                          NULL);
1384   GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1385   cp_map = NULL;
1386   GNUNET_free (trustDirectory);
1387   trustDirectory = NULL;
1388 }
1389
1390
1391 /**
1392  * Iterator to remove references to LC entry.
1393  *
1394  * @param the 'struct GSF_LocalClient*' to look for
1395  * @param key current key code
1396  * @param value value in the hash map (peer entry)
1397  * @return GNUNET_YES (we should continue to iterate)
1398  */
1399 static int 
1400 clean_local_client (void *cls,
1401                     const GNUNET_HashCode * key,
1402                     void *value)
1403 {
1404   const struct GSF_LocalClient *lc = cls;
1405   struct GSF_ConnectedPeer *cp = value;
1406   unsigned int i;
1407
1408   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1409     if (cp->ppd.last_client_replies[i] == lc)
1410       cp->ppd.last_client_replies[i] = NULL;
1411   return GNUNET_YES;
1412 }
1413
1414
1415 /**
1416  * Notification that a local client disconnected.  Clean up all of our
1417  * references to the given handle.
1418  *
1419  * @param lc handle to the local client (henceforth invalid)
1420  */
1421 void
1422 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1423 {
1424   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1425                                          &clean_local_client,
1426                                          (void*) lc);
1427 }
1428
1429
1430 /* end of gnunet-service-fs_cp.c */