no includes on top level please
[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  */
985 void
986 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
987                               struct GNUNET_TIME_Absolute request_time,
988                               uint32_t request_priority)
989 {
990   struct GNUNET_TIME_Relative delay;
991
992   delay = GNUNET_TIME_absolute_get_duration (request_time);  
993   cp->ppd.avg_reply_delay = (cp->ppd.avg_reply_delay * (RUNAVG_DELAY_N-1) + delay.rel_value) / RUNAVG_DELAY_N;
994   cp->ppd.avg_priority = (cp->avg_priority * (RUNAVG_DELAY_N-1) + request_priority) / RUNAVG_DELAY_N;
995 }
996
997
998 /**
999  * Report on receiving a reply in response to an initiating client.
1000  * Remember that this peer is good for this client.
1001  *
1002  * @param cp responding peer (will be updated)
1003  * @param initiator_client local client on responsible for query
1004  */
1005 void
1006 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1007                                    const struct GSF_LocalClient *initiator_client)
1008 {
1009   cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1010 }
1011
1012
1013 /**
1014  * Report on receiving a reply in response to an initiating peer.
1015  * Remember that this peer is good for this initiating peer.
1016  *
1017  * @param cp responding peer (will be updated)
1018  * @param initiator_peer other peer responsible for query
1019  */
1020 void
1021 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1022                                  const struct GSF_ConnectedPeer *initiator_peer)
1023 {
1024   GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
1025   cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff++ % P2P_SUCCESS_LIST_SIZE] = initiator_peer->pid;
1026   GNUNET_PEER_change_rc (initiator_peer->pid, 1);
1027 }
1028
1029
1030 /**
1031  * Method called whenever a given peer has a status change.
1032  *
1033  * @param cls closure
1034  * @param peer peer identity this notification is about
1035  * @param bandwidth_in available amount of inbound bandwidth
1036  * @param bandwidth_out available amount of outbound bandwidth
1037  * @param timeout absolute time when this peer will time out
1038  *        unless we see some further activity from it
1039  * @param atsi status information
1040  */
1041 void
1042 GSF_peer_status_handler_ (void *cls,
1043                           const struct GNUNET_PeerIdentity *peer,
1044                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1045                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1046                           struct GNUNET_TIME_Absolute timeout,
1047                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1048 {
1049   struct GSF_ConnectedPeer *cp;
1050
1051   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1052                                           &peer->hashPubKey);
1053   GNUNET_assert (NULL != cp);
1054   update_atsi (cp, atsi);
1055 }
1056
1057
1058 /**
1059  * Cancel all requests associated with the peer.
1060  *
1061  * @param cls unused
1062  * @param query hash code of the request
1063  * @param value the 'struct GSF_PendingRequest'
1064  * @return GNUNET_YES (continue to iterate)
1065  */
1066 static int
1067 cancel_pending_request (void *cls,
1068                         const GNUNET_HashCode *query,
1069                         void *value)
1070 {
1071   struct GSF_PendingRequest *pr = value;
1072
1073   GSF_pending_request_cancel_ (pr);
1074   return GNUNET_OK;
1075 }
1076
1077
1078 /**
1079  * A peer disconnected from us.  Tear down the connected peer
1080  * record.
1081  *
1082  * @param cls unused
1083  * @param peer identity of peer that connected
1084  */
1085 void
1086 GSF_peer_disconnect_handler_ (void *cls,
1087                               const struct GNUNET_PeerIdentity *peer)
1088 {
1089   struct GSF_ConnectedPeer *cp;
1090   struct GSF_PeerTransmitHandle *pth;
1091
1092   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1093                                           &peer->hashPubKey);
1094   GNUNET_assert (NULL != cp);
1095   GNUNET_CONTAINER_multihashmap_remove (cp_map,
1096                                         &peer->hashPubKey,
1097                                         cp);
1098   if (NULL != cp->migration_pth)
1099     {
1100       GSF_peer_transmit_cancel_ (cp->migration_pth);
1101       cp->migration_pth = NULL;
1102     }
1103   if (NULL != cp->irc)
1104     {
1105       GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1106       cp->irc = NULL;
1107     }
1108   GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1109                                          &cancel_pending_request,
1110                                          cp);
1111   GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1112   cp->request_map = NULL;
1113   GSF_plan_notify_peer_disconnect_ (cp);
1114   GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1115   GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1116   while (NULL != (pth = cp->pth_head))
1117     {
1118       if (NULL != pth->th)
1119         {
1120           GNUNET_CORE_notify_transmit_ready_cancel (pth->th);
1121           pth->th = NULL;
1122         }
1123       GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1124                                    cp->pth_tail,
1125                                    pth);
1126       GNUNET_free (pth);
1127     }
1128   GNUNET_PEER_change_rc (cp->pid, -1);
1129   GNUNET_free (cp);
1130 }
1131
1132
1133 /**
1134  * Closure for 'call_iterator'.
1135  */
1136 struct IterationContext
1137 {
1138   /**
1139    * Function to call on each entry.
1140    */
1141   GSF_ConnectedPeerIterator it;
1142
1143   /**
1144    * Closure for 'it'.
1145    */
1146   void *it_cls;
1147 };
1148
1149
1150 /**
1151  * Function that calls the callback for each peer.
1152  *
1153  * @param cls the 'struct IterationContext*'
1154  * @param key identity of the peer
1155  * @param value the 'struct GSF_ConnectedPeer*'
1156  * @return GNUNET_YES to continue iteration
1157  */
1158 static int
1159 call_iterator (void *cls,
1160                const GNUNET_HashCode *key,
1161                void *value)
1162 {
1163   struct IterationContext *ic = cls;
1164   struct GSF_ConnectedPeer *cp = value;
1165   
1166   ic->it (ic->it_cls,
1167           (const struct GNUNET_PeerIdentity*) key,
1168           cp,
1169           &cp->ppd);
1170   return GNUNET_YES;
1171 }
1172
1173
1174 /**
1175  * Iterate over all connected peers.
1176  *
1177  * @param it function to call for each peer
1178  * @param it_cls closure for it
1179  */
1180 void
1181 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1182                               void *it_cls)
1183 {
1184   struct IterationContext ic;
1185
1186   ic.it = it;
1187   ic.it_cls = it_cls;
1188   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1189                                          &call_iterator,
1190                                          &ic);
1191 }
1192
1193
1194 /**
1195  * Obtain the identity of a connected peer.
1196  *
1197  * @param cp peer to reserve bandwidth from
1198  * @param id identity to set (written to)
1199  */
1200 void
1201 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1202                                   struct GNUNET_PeerIdentity *id)
1203 {
1204   GNUNET_PEER_resolve (cp->pid,
1205                        &id);
1206 }
1207
1208
1209 /**
1210  * Assemble a migration stop message for transmission.
1211  *
1212  * @param cls the 'struct GSF_ConnectedPeer' to use
1213  * @param size number of bytes we're allowed to write to buf
1214  * @param buf where to copy the message
1215  * @return number of bytes copied to buf
1216  */
1217 static size_t
1218 create_migration_stop_message (void *cls,
1219                                size_t size,
1220                                void *buf)
1221 {
1222   struct GSF_ConnectedPeer *cp = cls;
1223   struct MigrationStopMessage msm;
1224
1225   cp->migration_pth = NULL;
1226   if (NULL == buf)
1227     return 0;
1228   GNUNET_assert (size > sizeof (struct MigrationStopMessage));
1229   msm.header.size = htons (sizeof (struct MigrationStopMessage));
1230   msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1231   msm.duration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block));
1232   memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1233   return sizeof (struct MigrationStopMessage);
1234 }
1235
1236
1237 /**
1238  * Ask a peer to stop migrating data to us until the given point
1239  * in time.
1240  * 
1241  * @param cp peer to ask
1242  * @param block_time until when to block
1243  */
1244 void
1245 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1246                            struct GNUNET_TIME_Relative block_time)
1247 {
1248   if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value > block_time.rel_value)
1249     return; /* already blocked */
1250   cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
1251   if (cp->migration_pth != NULL)
1252     GSF_peer_transmit_cancel_ (cp->migration_pth);
1253   cp->migration_pth 
1254     = GSF_peer_transmit_ (cp,
1255                           GNUNET_SYSERR,
1256                           UINT32_MAX,
1257                           GNUNET_TIME_UNIT_FOREVER_REL,
1258                           sizeof (struct MigrationStopMessage),
1259                           &create_migration_stop_message,
1260                           cp);
1261 }
1262
1263
1264 /**
1265  * Write host-trust information to a file - flush the buffer entry!
1266  *
1267  * @param cls closure, not used
1268  * @param key host identity
1269  * @param value the 'struct GSF_ConnectedPeer' to flush
1270  * @return GNUNET_OK to continue iteration
1271  */
1272 static int
1273 flush_trust (void *cls,
1274              const GNUNET_HashCode *key,
1275              void *value)
1276 {
1277   struct GSF_ConnectedPeer *cp = value;
1278   char *fn;
1279   uint32_t trust;
1280   struct GNUNET_PeerIdentity pid;
1281
1282   if (cp->trust == cp->disk_trust)
1283     return GNUNET_OK;                     /* unchanged */
1284   GNUNET_PEER_resolve (cp->pid,
1285                        &pid);
1286   fn = get_trust_filename (&pid);
1287   if (cp->trust == 0)
1288     {
1289       if ((0 != UNLINK (fn)) && (errno != ENOENT))
1290         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1291                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1292     }
1293   else
1294     {
1295       trust = htonl (cp->trust);
1296       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
1297                                                     sizeof(uint32_t),
1298                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1299                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1300         cp->disk_trust = cp->trust;
1301     }
1302   GNUNET_free (fn);
1303   return GNUNET_OK;
1304 }
1305
1306
1307 /**
1308  * Notify core about a preference we have for the given peer
1309  * (to allocate more resources towards it).  The change will
1310  * be communicated the next time we reserve bandwidth with
1311  * core (not instantly).
1312  *
1313  * @param cp peer to reserve bandwidth from
1314  * @param pref preference change
1315  */
1316 void
1317 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1318                                        uint64_t pref)
1319 {
1320   cp->inc_preference += pref;
1321 }
1322
1323
1324 /**
1325  * Call this method periodically to flush trust information to disk.
1326  *
1327  * @param cls closure, not used
1328  * @param tc task context, not used
1329  */
1330 static void
1331 cron_flush_trust (void *cls,
1332                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1333 {
1334
1335   if (NULL == cp_map)
1336     return;
1337   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1338                                          &flush_trust,
1339                                          NULL);
1340   if (NULL == tc)
1341     return;
1342   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1343     return;
1344   GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, 
1345                                 &cron_flush_trust, 
1346                                 NULL);
1347 }
1348
1349
1350 /**
1351  * Initialize peer management subsystem.
1352  *
1353  * @param cfg configuration to use
1354  */
1355 void
1356 GSF_connected_peer_init_ (struct GNUNET_CONFIGURATION_Handle *cfg)
1357 {
1358   cp_map = GNUNET_CONTAINER_multihashmap_create (128);
1359   GNUNET_assert (GNUNET_OK ==
1360                  GNUNET_CONFIGURATION_get_value_filename (cfg,
1361                                                           "fs",
1362                                                           "TRUST",
1363                                                           &trustDirectory));
1364   GNUNET_DISK_directory_create (trustDirectory);
1365   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1366                                       &cron_flush_trust, NULL);
1367 }
1368
1369
1370 /**
1371  * Iterator to free peer entries.
1372  *
1373  * @param cls closure, unused
1374  * @param key current key code
1375  * @param value value in the hash map (peer entry)
1376  * @return GNUNET_YES (we should continue to iterate)
1377  */
1378 static int 
1379 clean_peer (void *cls,
1380             const GNUNET_HashCode * key,
1381             void *value)
1382 {
1383   GSF_peer_disconnect_handler_ (NULL, 
1384                                 (const struct GNUNET_PeerIdentity*) key);
1385   return GNUNET_YES;
1386 }
1387
1388
1389 /**
1390  * Shutdown peer management subsystem.
1391  */
1392 void
1393 GSF_connected_peer_done_ ()
1394 {
1395   cron_flush_trust (NULL, NULL);
1396   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1397                                          &clean_peer,
1398                                          NULL);
1399   GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1400   cp_map = NULL;
1401   GNUNET_free (trustDirectory);
1402   trustDirectory = NULL;
1403 }
1404
1405
1406 /**
1407  * Iterator to remove references to LC entry.
1408  *
1409  * @param the 'struct GSF_LocalClient*' to look for
1410  * @param key current key code
1411  * @param value value in the hash map (peer entry)
1412  * @return GNUNET_YES (we should continue to iterate)
1413  */
1414 static int 
1415 clean_local_client (void *cls,
1416                     const GNUNET_HashCode * key,
1417                     void *value)
1418 {
1419   const struct GSF_LocalClient *lc = cls;
1420   struct GSF_ConnectedPeer *cp = value;
1421   unsigned int i;
1422
1423   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1424     if (cp->ppd.last_client_replies[i] == lc)
1425       cp->ppd.last_client_replies[i] = NULL;
1426   return GNUNET_YES;
1427 }
1428
1429
1430 /**
1431  * Notification that a local client disconnected.  Clean up all of our
1432  * references to the given handle.
1433  *
1434  * @param lc handle to the local client (henceforth invalid)
1435  */
1436 void
1437 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1438 {
1439   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1440                                          &clean_local_client,
1441                                          (void*) lc);
1442 }
1443
1444
1445 /* end of gnunet-service-fs_cp.c */