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