delay as needed
[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                   0, NULL);
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   prd = GSF_pending_request_get_data_ (pr);
634   if (NULL == data)
635     {
636       GNUNET_STATISTICS_update (GSF_stats,
637                                 gettext_noop ("# P2P searches active"),
638                                 -1,
639                                 GNUNET_NO);
640       GNUNET_break (GNUNET_OK ==
641                     GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
642                                                           &prd->query,
643                                                           pr));
644       return;
645     }  
646   GNUNET_break (type != GNUNET_BLOCK_TYPE_ANY);
647   if ( (prd->type != type) &&
648        (prd->type != GNUNET_BLOCK_TYPE_ANY) )
649     {
650       GNUNET_break (0);
651       return;
652     }
653 #if DEBUG_FS
654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
655               "Transmitting result for query `%s'\n",
656               GNUNET_h2s (&prd->query));
657 #endif  
658   GNUNET_STATISTICS_update (GSF_stats,
659                             gettext_noop ("# replies received for other peers"),
660                             1,
661                             GNUNET_NO); 
662   msize = sizeof (struct PutMessage) + data_len;
663   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
664     {
665       GNUNET_break (0);
666       return;
667     }
668   pm = GNUNET_malloc (sizeof (msize));
669   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
670   pm->header.size = htons (msize);
671   pm->type = htonl (type);
672   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
673   memcpy (&pm[1], data, data_len);
674   (void) GSF_peer_transmit_ (cp, GNUNET_NO,
675                              UINT32_MAX,
676                              REPLY_TIMEOUT,
677                              msize,
678                              &copy_reply,
679                              pm);
680 }
681
682
683 /**
684  * Increase the host credit by a value.
685  *
686  * @param cp which peer to change the trust value on
687  * @param value is the int value by which the
688  *  host credit is to be increased or decreased
689  * @returns the actual change in trust (positive or negative)
690  */
691 static int
692 change_host_trust (struct GSF_ConnectedPeer *cp, int value)
693 {
694   if (value == 0)
695     return 0;
696   GNUNET_assert (cp != NULL);
697   if (value > 0)
698     {
699       if (cp->ppd.trust + value < cp->ppd.trust)
700         {
701           value = UINT32_MAX - cp->ppd.trust;
702           cp->ppd.trust = UINT32_MAX;
703         }
704       else
705         cp->ppd.trust += value;
706     }
707   else
708     {
709       if (cp->ppd.trust < -value)
710         {
711           value = -cp->ppd.trust;
712           cp->ppd.trust = 0;
713         }
714       else
715         cp->ppd.trust += value;
716     }
717   return value;
718 }
719
720
721 /**
722  * We've received a request with the specified priority.  Bound it
723  * according to how much we trust the given peer.
724  * 
725  * @param prio_in requested priority
726  * @param cp the peer making the request
727  * @return effective priority
728  */
729 static int32_t
730 bound_priority (uint32_t prio_in,
731                 struct GSF_ConnectedPeer *cp)
732 {
733 #define N ((double)128.0)
734   uint32_t ret;
735   double rret;
736   int ld;
737
738   ld = GSF_test_get_load_too_high_ (0);
739   if (ld == GNUNET_SYSERR)
740     {
741       GNUNET_STATISTICS_update (GSF_stats,
742                                 gettext_noop ("# requests done for free (low load)"),
743                                 1,
744                                 GNUNET_NO);
745       return 0; /* excess resources */
746     }
747   if (prio_in > INT32_MAX)
748     prio_in = INT32_MAX;
749   ret = - change_host_trust (cp, - (int) prio_in);
750   if (ret > 0)
751     {
752       if (ret > GSF_current_priorities + N)
753         rret = GSF_current_priorities + N;
754       else
755         rret = ret;
756       GSF_current_priorities 
757         = (GSF_current_priorities * (N-1) + rret)/N;
758     }
759   if ( (ld == GNUNET_YES) && (ret > 0) )
760     {
761       /* try with charging */
762       ld = GSF_test_get_load_too_high_ (ret);
763     }
764   if (ld == GNUNET_YES)
765     {
766       GNUNET_STATISTICS_update (GSF_stats,
767                                 gettext_noop ("# request dropped, priority insufficient"),
768                                 1,
769                                 GNUNET_NO);
770       /* undo charge */
771       change_host_trust (cp, (int) ret);
772       return -1; /* not enough resources */
773     }
774   else
775     {
776       GNUNET_STATISTICS_update (GSF_stats,
777                                 gettext_noop ("# requests done for a price (normal load)"),
778                                 1,
779                                 GNUNET_NO);
780     }
781 #undef N
782   return ret;
783 }
784
785
786 /**
787  * The priority level imposes a bound on the maximum
788  * value for the ttl that can be requested.
789  *
790  * @param ttl_in requested ttl
791  * @param prio given priority
792  * @return ttl_in if ttl_in is below the limit,
793  *         otherwise the ttl-limit for the given priority
794  */
795 static int32_t
796 bound_ttl (int32_t ttl_in, uint32_t prio)
797 {
798   unsigned long long allowed;
799
800   if (ttl_in <= 0)
801     return ttl_in;
802   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
803   if (ttl_in > allowed)      
804     {
805       if (allowed >= (1 << 30))
806         return 1 << 30;
807       return allowed;
808     }
809   return ttl_in;
810 }
811
812
813 /**
814  * Handle P2P "QUERY" message.  Creates the pending request entry
815  * and sets up all of the data structures to that we will
816  * process replies properly.  Does not initiate forwarding or
817  * local database lookups.
818  *
819  * @param other the other peer involved (sender or receiver, NULL
820  *        for loopback messages where we are both sender and receiver)
821  * @param message the actual message
822  * @return pending request handle, NULL on error
823  */
824 struct GSF_PendingRequest *
825 GSF_handle_p2p_query_ (const struct GNUNET_PeerIdentity *other,
826                        const struct GNUNET_MessageHeader *message)
827 {
828   struct GSF_PendingRequest *pr;
829   struct GSF_PendingRequestData *prd;
830   struct GSF_ConnectedPeer *cp;
831   struct GSF_ConnectedPeer *cps;
832   const GNUNET_HashCode *namespace;
833   const struct GNUNET_PeerIdentity *target;
834   enum GSF_PendingRequestOptions options;                            
835   uint16_t msize;
836   const struct GetMessage *gm;
837   unsigned int bits;
838   const GNUNET_HashCode *opt;
839   uint32_t bm;
840   size_t bfsize;
841   uint32_t ttl_decrement;
842   int32_t priority;
843   int32_t ttl;
844   enum GNUNET_BLOCK_Type type;
845   GNUNET_PEER_Id spid;
846
847   msize = ntohs(message->size);
848   if (msize < sizeof (struct GetMessage))
849     {
850       GNUNET_break_op (0);
851       return NULL;
852     }
853   gm = (const struct GetMessage*) message;
854 #if DEBUG_FS
855   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
856               "Received request for `%s'\n",
857               GNUNET_h2s (&gm->query));
858 #endif
859   type = ntohl (gm->type);
860   bm = ntohl (gm->hash_bitmap);
861   bits = 0;
862   while (bm > 0)
863     {
864       if (1 == (bm & 1))
865         bits++;
866       bm >>= 1;
867     }
868   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
869     {
870       GNUNET_break_op (0);
871       return NULL;
872     }  
873   opt = (const GNUNET_HashCode*) &gm[1];
874   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
875   /* bfsize must be power of 2, check! */
876   if (0 != ( (bfsize - 1) & bfsize))
877     {
878       GNUNET_break_op (0);
879       return NULL;
880     }
881   GSF_cover_query_count++;
882   bm = ntohl (gm->hash_bitmap);
883   bits = 0;
884   cps = GNUNET_CONTAINER_multihashmap_get (cp_map,
885                                            &other->hashPubKey);
886   if (NULL == cps)
887     {
888       /* peer must have just disconnected */
889       GNUNET_STATISTICS_update (GSF_stats,
890                                 gettext_noop ("# requests dropped due to initiator not being connected"),
891                                 1,
892                                 GNUNET_NO);
893       return NULL;
894     }
895   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
896     cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
897                                             &opt[bits++]);
898   else
899     cp = cps;
900   if (cp == NULL)
901     {
902 #if DEBUG_FS
903       if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
904         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
905                     "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
906                     GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
907       
908       else
909         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
910                     "Failed to find peer `%4s' in connection set. Dropping query.\n",
911                     GNUNET_i2s (other));
912 #endif
913       GNUNET_STATISTICS_update (GSF_stats,
914                                 gettext_noop ("# requests dropped due to missing reverse route"),
915                                 1,
916                                 GNUNET_NO);
917       return NULL;
918     }
919   /* note that we can really only check load here since otherwise
920      peers could find out that we are overloaded by not being
921      disconnected after sending us a malformed query... */
922   priority = bound_priority (ntohl (gm->priority), cps);
923   if (priority < 0)
924     {
925 #if DEBUG_FS
926       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927                   "Dropping query from `%s', this peer is too busy.\n",
928                   GNUNET_i2s (other));
929 #endif
930       return NULL;
931     }
932 #if DEBUG_FS 
933   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
935               GNUNET_h2s (&gm->query),
936               (unsigned int) type,
937               GNUNET_i2s (other),
938               (unsigned int) bm);
939 #endif
940   namespace = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) ? &opt[bits++] : NULL;
941   target = (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? ((const struct GNUNET_PeerIdentity*) &opt[bits++]) : NULL;
942   options = 0;
943   spid = 0;
944   if ( (GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + priority)) ||
945        (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) > 
946         GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)) )
947     {
948       /* don't have BW to send to peer, or would likely take longer than we have for it,
949          so at best indirect the query */
950       priority = 0;
951       options |= GSF_PRO_FORWARD_ONLY;
952       spid = GNUNET_PEER_intern (other);
953     }
954   ttl = bound_ttl (ntohl (gm->ttl), priority);
955   /* decrement ttl (always) */
956   ttl_decrement = 2 * TTL_DECREMENT +
957     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
958                               TTL_DECREMENT);
959   if ( (ttl < 0) &&
960        (((int32_t)(ttl - ttl_decrement)) > 0) )
961     {
962 #if DEBUG_FS
963       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964                   "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
965                   GNUNET_i2s (other),
966                   ttl,
967                   ttl_decrement);
968 #endif
969       GNUNET_STATISTICS_update (GSF_stats,
970                                 gettext_noop ("# requests dropped due TTL underflow"),
971                                 1,
972                                 GNUNET_NO);
973       /* integer underflow => drop (should be very rare)! */      
974       return NULL;
975     } 
976   ttl -= ttl_decrement;
977
978   /* test if the request already exists */
979   pr = GNUNET_CONTAINER_multihashmap_get (cp->request_map,
980                                           &gm->query);
981   if (pr != NULL) 
982     {      
983       prd = GSF_pending_request_get_data_ (pr);
984       if ( (prd->type == type) &&
985            ( (type != GNUNET_BLOCK_TYPE_FS_SBLOCK) ||
986              (0 == memcmp (&prd->namespace,
987                            namespace,
988                            sizeof (GNUNET_HashCode))) ) )
989         {
990           if (prd->ttl.abs_value >= GNUNET_TIME_absolute_get().abs_value + ttl)
991             {
992               /* existing request has higher TTL, drop new one! */
993               prd->priority += priority;
994 #if DEBUG_FS
995               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
996                           "Have existing request with higher TTL, dropping new request.\n",
997                           GNUNET_i2s (other));
998 #endif
999               GNUNET_STATISTICS_update (GSF_stats,
1000                                         gettext_noop ("# requests dropped due to higher-TTL request"),
1001                                         1,
1002                                         GNUNET_NO);
1003               return NULL;
1004             }
1005           /* existing request has lower TTL, drop old one! */
1006           priority += prd->priority;
1007           GSF_pending_request_cancel_ (pr);
1008           GNUNET_assert (GNUNET_YES ==
1009                          GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
1010                                                                &gm->query,
1011                                                                pr));
1012         }
1013     }
1014   
1015   pr = GSF_pending_request_create_ (options,
1016                                     type,
1017                                     &gm->query,
1018                                     namespace,
1019                                     target,
1020                                     (bfsize > 0) ? (const char*)&opt[bits] : NULL,
1021                                     bfsize,
1022                                     ntohl (gm->filter_mutator),
1023                                     1 /* anonymity */,
1024                                     (uint32_t) priority,
1025                                     ttl,
1026                                     spid,
1027                                     NULL, 0, /* replies_seen */
1028                                     &handle_p2p_reply,
1029                                     cp);
1030   GNUNET_break (GNUNET_OK ==
1031                 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1032                                                    &gm->query,
1033                                                    pr,
1034                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1035   GNUNET_STATISTICS_update (GSF_stats,
1036                             gettext_noop ("# P2P searches received"),
1037                             1,
1038                             GNUNET_NO);
1039   GNUNET_STATISTICS_update (GSF_stats,
1040                             gettext_noop ("# P2P searches active"),
1041                             1,
1042                             GNUNET_NO);
1043   return pr;
1044 }
1045
1046
1047 /**
1048  * Function called if there has been a timeout trying to satisfy
1049  * a transmission request.
1050  *
1051  * @param cls the 'struct GSF_PeerTransmitHandle' of the request 
1052  * @param tc scheduler context
1053  */
1054 static void
1055 peer_transmit_timeout (void *cls,
1056                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1057 {
1058   struct GSF_PeerTransmitHandle *pth = cls;
1059   struct GSF_ConnectedPeer *cp;
1060   
1061   pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1062   cp = pth->cp;
1063   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1064                                cp->pth_tail,
1065                                pth);
1066   if (GNUNET_YES == pth->is_query)
1067     GNUNET_assert (0 < cp->ppd.pending_queries--);    
1068   else if (GNUNET_NO == pth->is_query)
1069     GNUNET_assert (0 < cp->ppd.pending_replies--);
1070   GNUNET_LOAD_update (cp->ppd.transmission_delay,
1071                       UINT64_MAX);
1072   pth->gmc (pth->gmc_cls, 
1073             0, NULL);
1074   GNUNET_free (pth);
1075 }
1076
1077
1078 /**
1079  * Transmit a message to the given peer as soon as possible.
1080  * If the peer disconnects before the transmission can happen,
1081  * the callback is invoked with a 'NULL' buffer.
1082  *
1083  * @param cp target peer
1084  * @param is_query is this a query (GNUNET_YES) or content (GNUNET_NO) or neither (GNUNET_SYSERR)
1085  * @param priority how important is this request?
1086  * @param timeout when does this request timeout (call gmc with error)
1087  * @param size number of bytes we would like to send to the peer
1088  * @param gmc function to call to get the message
1089  * @param gmc_cls closure for gmc
1090  * @return handle to cancel request
1091  */
1092 struct GSF_PeerTransmitHandle *
1093 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1094                     int is_query,
1095                     uint32_t priority,
1096                     struct GNUNET_TIME_Relative timeout,
1097                     size_t size,
1098                     GSF_GetMessageCallback gmc,
1099                     void *gmc_cls)
1100 {
1101   struct GSF_PeerTransmitHandle *pth;
1102   struct GSF_PeerTransmitHandle *pos;
1103   struct GSF_PeerTransmitHandle *prev;
1104   struct GNUNET_PeerIdentity target;
1105   uint64_t ip;
1106   int is_ready;
1107
1108   pth = GNUNET_malloc (sizeof (struct GSF_PeerTransmitHandle));
1109   pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1110   pth->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1111   pth->gmc = gmc;
1112   pth->gmc_cls = gmc_cls;
1113   pth->size = size;
1114   pth->is_query = is_query;
1115   pth->priority = priority;
1116   pth->cp = cp;
1117   /* insertion sort (by priority, descending) */
1118   prev = NULL;
1119   pos = cp->pth_head;
1120   while ( (pos != NULL) &&
1121           (pos->priority > priority) )
1122     {
1123       prev = pos;
1124       pos = pos->next;
1125     }
1126   if (prev == NULL)
1127     GNUNET_CONTAINER_DLL_insert (cp->pth_head,
1128                                  cp->pth_tail,
1129                                  pth);
1130   else
1131     GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1132                                        cp->pth_tail,
1133                                        prev,
1134                                        pth);
1135   GNUNET_PEER_resolve (cp->ppd.pid,
1136                        &target);
1137   if (GNUNET_YES == is_query)
1138     {
1139       /* query, need reservation */
1140       cp->ppd.pending_queries++;
1141       if (GNUNET_YES == cp->did_reserve)
1142         {
1143           cp->did_reserve = GNUNET_NO;
1144           /* reservation already done! */
1145           is_ready = GNUNET_YES;
1146           ip = cp->inc_preference;
1147           cp->inc_preference = 0;
1148           cp->irc = GNUNET_CORE_peer_change_preference (GSF_core,
1149                                                         &target,
1150                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1151                                                         GNUNET_BANDWIDTH_VALUE_MAX,
1152                                                         DBLOCK_SIZE,
1153                                                         ip,
1154                                                         &core_reserve_callback,
1155                                                         cp);      
1156         }
1157       else
1158         {
1159           /* still waiting for reservation */
1160           is_ready = GNUNET_NO;
1161         }
1162     }
1163   else if (GNUNET_NO == is_query)
1164     {
1165       /* no reservation needed for content */
1166       cp->ppd.pending_replies++;
1167       is_ready = GNUNET_YES;
1168     }
1169   else
1170     {
1171       /* not a query or content, no reservation needed */
1172       is_ready = GNUNET_YES;
1173     }
1174   if (is_ready)
1175     {
1176       pth->cth = GNUNET_CORE_notify_transmit_ready (GSF_core,
1177                                                     GNUNET_YES,
1178                                                     priority,
1179                                                     timeout,
1180                                                     &target,
1181                                                     size,
1182                                                     &peer_transmit_ready_cb,
1183                                                     pth);
1184       /* pth->cth could be NULL here, that's OK, we'll try again
1185          later... */
1186     }
1187   if (pth->cth == NULL)
1188     {
1189       /* if we're waiting for reservation OR if we could not do notify_transmit_ready,
1190          install a timeout task to be on the safe side */
1191       pth->timeout_task = GNUNET_SCHEDULER_add_delayed (timeout,
1192                                                         &peer_transmit_timeout,
1193                                                         pth);
1194     }
1195   return pth;
1196 }
1197
1198
1199 /**
1200  * Cancel an earlier request for transmission.
1201  *
1202  * @param pth request to cancel
1203  */
1204 void
1205 GSF_peer_transmit_cancel_ (struct GSF_PeerTransmitHandle *pth)
1206 {
1207   struct GSF_ConnectedPeer *cp;
1208
1209   if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1210     {
1211       GNUNET_SCHEDULER_cancel (pth->timeout_task);
1212       pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1213     }
1214   if (NULL != pth->cth)
1215     {
1216       GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1217       pth->cth = NULL;
1218     }
1219   cp = pth->cp;
1220   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1221                                cp->pth_tail,
1222                                pth);
1223   if (GNUNET_YES == pth->is_query)
1224     GNUNET_assert (0 < cp->ppd.pending_queries--);    
1225   else if (GNUNET_NO == pth->is_query)
1226     GNUNET_assert (0 < cp->ppd.pending_replies--);
1227   GNUNET_free (pth);
1228 }
1229
1230
1231 /**
1232  * Report on receiving a reply; update the performance record of the given peer.
1233  *
1234  * @param cp responding peer (will be updated)
1235  * @param request_time time at which the original query was transmitted
1236  * @param request_priority priority of the original request
1237  */
1238 void
1239 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1240                               struct GNUNET_TIME_Absolute request_time,
1241                               uint32_t request_priority)
1242 {
1243   struct GNUNET_TIME_Relative delay;
1244
1245   delay = GNUNET_TIME_absolute_get_duration (request_time);  
1246   cp->ppd.avg_reply_delay.rel_value = (cp->ppd.avg_reply_delay.rel_value * (RUNAVG_DELAY_N-1) + delay.rel_value) / RUNAVG_DELAY_N;
1247   cp->ppd.avg_priority = (cp->ppd.avg_priority * (RUNAVG_DELAY_N-1) + request_priority) / RUNAVG_DELAY_N;
1248 }
1249
1250
1251 /**
1252  * Report on receiving a reply in response to an initiating client.
1253  * Remember that this peer is good for this client.
1254  *
1255  * @param cp responding peer (will be updated)
1256  * @param initiator_client local client on responsible for query
1257  */
1258 void
1259 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1260                                    struct GSF_LocalClient *initiator_client)
1261 {
1262   cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1263 }
1264
1265
1266 /**
1267  * Report on receiving a reply in response to an initiating peer.
1268  * Remember that this peer is good for this initiating peer.
1269  *
1270  * @param cp responding peer (will be updated)
1271  * @param initiator_peer other peer responsible for query
1272  */
1273 void
1274 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1275                                  const struct GSF_ConnectedPeer *initiator_peer)
1276 {
1277   GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
1278   cp->ppd.last_p2p_replies[cp->last_p2p_replies_woff++ % P2P_SUCCESS_LIST_SIZE] = initiator_peer->ppd.pid;
1279   GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1280 }
1281
1282
1283 /**
1284  * Method called whenever a given peer has a status change.
1285  *
1286  * @param cls closure
1287  * @param peer peer identity this notification is about
1288  * @param bandwidth_in available amount of inbound bandwidth
1289  * @param bandwidth_out available amount of outbound bandwidth
1290  * @param timeout absolute time when this peer will time out
1291  *        unless we see some further activity from it
1292  * @param atsi status information
1293  */
1294 void
1295 GSF_peer_status_handler_ (void *cls,
1296                           const struct GNUNET_PeerIdentity *peer,
1297                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1298                           struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1299                           struct GNUNET_TIME_Absolute timeout,
1300                           const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1301 {
1302   struct GSF_ConnectedPeer *cp;
1303
1304   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1305                                           &peer->hashPubKey);
1306   GNUNET_assert (NULL != cp);
1307   update_atsi (cp, atsi);
1308 }
1309
1310
1311 /**
1312  * Cancel all requests associated with the peer.
1313  *
1314  * @param cls unused
1315  * @param query hash code of the request
1316  * @param value the 'struct GSF_PendingRequest'
1317  * @return GNUNET_YES (continue to iterate)
1318  */
1319 static int
1320 cancel_pending_request (void *cls,
1321                         const GNUNET_HashCode *query,
1322                         void *value)
1323 {
1324   struct GSF_PendingRequest *pr = value;
1325
1326   GSF_pending_request_cancel_ (pr);
1327   return GNUNET_OK;
1328 }
1329
1330
1331 /**
1332  * A peer disconnected from us.  Tear down the connected peer
1333  * record.
1334  *
1335  * @param cls unused
1336  * @param peer identity of peer that connected
1337  */
1338 void
1339 GSF_peer_disconnect_handler_ (void *cls,
1340                               const struct GNUNET_PeerIdentity *peer)
1341 {
1342   struct GSF_ConnectedPeer *cp;
1343   struct GSF_PeerTransmitHandle *pth;
1344
1345   cp = GNUNET_CONTAINER_multihashmap_get (cp_map,
1346                                           &peer->hashPubKey);
1347   if (NULL == cp)
1348     return; /* must have been disconnect from core with
1349                'peer' == my_id, ignore */
1350   GNUNET_CONTAINER_multihashmap_remove (cp_map,
1351                                         &peer->hashPubKey,
1352                                         cp);
1353   if (NULL != cp->migration_pth)
1354     {
1355       GSF_peer_transmit_cancel_ (cp->migration_pth);
1356       cp->migration_pth = NULL;
1357     }
1358   if (NULL != cp->irc)
1359     {
1360       GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1361       cp->irc = NULL;
1362     }
1363   if (GNUNET_SCHEDULER_NO_TASK != cp->irc_delay_task)
1364     {
1365       GNUNET_SCHEDULER_cancel (cp->irc_delay_task);
1366       cp->irc_delay_task = GNUNET_SCHEDULER_NO_TASK;
1367     }
1368   GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1369                                          &cancel_pending_request,
1370                                          cp);
1371   GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1372   cp->request_map = NULL;
1373   GSF_plan_notify_peer_disconnect_ (cp);
1374   GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1375   GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1376   while (NULL != (pth = cp->pth_head))
1377     {
1378       if (NULL != pth->cth)
1379         {
1380           GNUNET_CORE_notify_transmit_ready_cancel (pth->cth);
1381           pth->cth = NULL;
1382         }
1383       GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1384                                    cp->pth_tail,
1385                                    pth);
1386       GNUNET_free (pth);
1387     }
1388   GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1389   if (GNUNET_SCHEDULER_NO_TASK != cp->mig_revive_task)
1390     {
1391       GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1392       cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
1393     }
1394   GNUNET_free (cp);
1395 }
1396
1397
1398 /**
1399  * Closure for 'call_iterator'.
1400  */
1401 struct IterationContext
1402 {
1403   /**
1404    * Function to call on each entry.
1405    */
1406   GSF_ConnectedPeerIterator it;
1407
1408   /**
1409    * Closure for 'it'.
1410    */
1411   void *it_cls;
1412 };
1413
1414
1415 /**
1416  * Function that calls the callback for each peer.
1417  *
1418  * @param cls the 'struct IterationContext*'
1419  * @param key identity of the peer
1420  * @param value the 'struct GSF_ConnectedPeer*'
1421  * @return GNUNET_YES to continue iteration
1422  */
1423 static int
1424 call_iterator (void *cls,
1425                const GNUNET_HashCode *key,
1426                void *value)
1427 {
1428   struct IterationContext *ic = cls;
1429   struct GSF_ConnectedPeer *cp = value;
1430   
1431   ic->it (ic->it_cls,
1432           (const struct GNUNET_PeerIdentity*) key,
1433           cp,
1434           &cp->ppd);
1435   return GNUNET_YES;
1436 }
1437
1438
1439 /**
1440  * Iterate over all connected peers.
1441  *
1442  * @param it function to call for each peer
1443  * @param it_cls closure for it
1444  */
1445 void
1446 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1447                               void *it_cls)
1448 {
1449   struct IterationContext ic;
1450
1451   ic.it = it;
1452   ic.it_cls = it_cls;
1453   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1454                                          &call_iterator,
1455                                          &ic);
1456 }
1457
1458
1459 /**
1460  * Obtain the identity of a connected peer.
1461  *
1462  * @param cp peer to reserve bandwidth from
1463  * @param id identity to set (written to)
1464  */
1465 void
1466 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1467                                   struct GNUNET_PeerIdentity *id)
1468 {
1469   GNUNET_PEER_resolve (cp->ppd.pid,
1470                        id);
1471 }
1472
1473
1474 /**
1475  * Assemble a migration stop message for transmission.
1476  *
1477  * @param cls the 'struct GSF_ConnectedPeer' to use
1478  * @param size number of bytes we're allowed to write to buf
1479  * @param buf where to copy the message
1480  * @return number of bytes copied to buf
1481  */
1482 static size_t
1483 create_migration_stop_message (void *cls,
1484                                size_t size,
1485                                void *buf)
1486 {
1487   struct GSF_ConnectedPeer *cp = cls;
1488   struct MigrationStopMessage msm;
1489
1490   cp->migration_pth = NULL;
1491   if (NULL == buf)
1492     return 0;
1493   GNUNET_assert (size > sizeof (struct MigrationStopMessage));
1494   msm.header.size = htons (sizeof (struct MigrationStopMessage));
1495   msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1496   msm.duration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (cp->last_migration_block));
1497   memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1498   return sizeof (struct MigrationStopMessage);
1499 }
1500
1501
1502 /**
1503  * Ask a peer to stop migrating data to us until the given point
1504  * in time.
1505  * 
1506  * @param cp peer to ask
1507  * @param block_time until when to block
1508  */
1509 void
1510 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1511                            struct GNUNET_TIME_Relative block_time)
1512 {
1513   if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value > block_time.rel_value)
1514     return; /* already blocked */
1515   cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
1516   if (cp->migration_pth != NULL)
1517     GSF_peer_transmit_cancel_ (cp->migration_pth);
1518   cp->migration_pth 
1519     = GSF_peer_transmit_ (cp,
1520                           GNUNET_SYSERR,
1521                           UINT32_MAX,
1522                           GNUNET_TIME_UNIT_FOREVER_REL,
1523                           sizeof (struct MigrationStopMessage),
1524                           &create_migration_stop_message,
1525                           cp);
1526 }
1527
1528
1529 /**
1530  * Write host-trust information to a file - flush the buffer entry!
1531  *
1532  * @param cls closure, not used
1533  * @param key host identity
1534  * @param value the 'struct GSF_ConnectedPeer' to flush
1535  * @return GNUNET_OK to continue iteration
1536  */
1537 static int
1538 flush_trust (void *cls,
1539              const GNUNET_HashCode *key,
1540              void *value)
1541 {
1542   struct GSF_ConnectedPeer *cp = value;
1543   char *fn;
1544   uint32_t trust;
1545   struct GNUNET_PeerIdentity pid;
1546
1547   if (cp->ppd.trust == cp->disk_trust)
1548     return GNUNET_OK;                     /* unchanged */
1549   GNUNET_PEER_resolve (cp->ppd.pid,
1550                        &pid);
1551   fn = get_trust_filename (&pid);
1552   if (cp->ppd.trust == 0)
1553     {
1554       if ((0 != UNLINK (fn)) && (errno != ENOENT))
1555         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1556                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1557     }
1558   else
1559     {
1560       trust = htonl (cp->ppd.trust);
1561       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
1562                                                     sizeof(uint32_t),
1563                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1564                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1565         cp->disk_trust = cp->ppd.trust;
1566     }
1567   GNUNET_free (fn);
1568   return GNUNET_OK;
1569 }
1570
1571
1572 /**
1573  * Notify core about a preference we have for the given peer
1574  * (to allocate more resources towards it).  The change will
1575  * be communicated the next time we reserve bandwidth with
1576  * core (not instantly).
1577  *
1578  * @param cp peer to reserve bandwidth from
1579  * @param pref preference change
1580  */
1581 void
1582 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1583                                        uint64_t pref)
1584 {
1585   cp->inc_preference += pref;
1586 }
1587
1588
1589 /**
1590  * Call this method periodically to flush trust information to disk.
1591  *
1592  * @param cls closure, not used
1593  * @param tc task context, not used
1594  */
1595 static void
1596 cron_flush_trust (void *cls,
1597                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1598 {
1599
1600   if (NULL == cp_map)
1601     return;
1602   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1603                                          &flush_trust,
1604                                          NULL);
1605   if (NULL == tc)
1606     return;
1607   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1608     return;
1609   GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, 
1610                                 &cron_flush_trust, 
1611                                 NULL);
1612 }
1613
1614
1615 /**
1616  * Initialize peer management subsystem.
1617  */
1618 void
1619 GSF_connected_peer_init_ ()
1620 {
1621   cp_map = GNUNET_CONTAINER_multihashmap_create (128);
1622   GNUNET_assert (GNUNET_OK ==
1623                  GNUNET_CONFIGURATION_get_value_filename (GSF_cfg,
1624                                                           "fs",
1625                                                           "TRUST",
1626                                                           &trustDirectory));
1627   GNUNET_DISK_directory_create (trustDirectory);
1628   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1629                                       &cron_flush_trust, NULL);
1630 }
1631
1632
1633 /**
1634  * Iterator to free peer entries.
1635  *
1636  * @param cls closure, unused
1637  * @param key current key code
1638  * @param value value in the hash map (peer entry)
1639  * @return GNUNET_YES (we should continue to iterate)
1640  */
1641 static int 
1642 clean_peer (void *cls,
1643             const GNUNET_HashCode * key,
1644             void *value)
1645 {
1646   GSF_peer_disconnect_handler_ (NULL, 
1647                                 (const struct GNUNET_PeerIdentity*) key);
1648   return GNUNET_YES;
1649 }
1650
1651
1652 /**
1653  * Shutdown peer management subsystem.
1654  */
1655 void
1656 GSF_connected_peer_done_ ()
1657 {
1658   cron_flush_trust (NULL, NULL);
1659   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1660                                          &clean_peer,
1661                                          NULL);
1662   GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1663   cp_map = NULL;
1664   GNUNET_free (trustDirectory);
1665   trustDirectory = NULL;
1666 }
1667
1668
1669 /**
1670  * Iterator to remove references to LC entry.
1671  *
1672  * @param cls the 'struct GSF_LocalClient*' to look for
1673  * @param key current key code
1674  * @param value value in the hash map (peer entry)
1675  * @return GNUNET_YES (we should continue to iterate)
1676  */
1677 static int 
1678 clean_local_client (void *cls,
1679                     const GNUNET_HashCode * key,
1680                     void *value)
1681 {
1682   const struct GSF_LocalClient *lc = cls;
1683   struct GSF_ConnectedPeer *cp = value;
1684   unsigned int i;
1685
1686   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1687     if (cp->ppd.last_client_replies[i] == lc)
1688       cp->ppd.last_client_replies[i] = NULL;
1689   return GNUNET_YES;
1690 }
1691
1692
1693 /**
1694  * Notification that a local client disconnected.  Clean up all of our
1695  * references to the given handle.
1696  *
1697  * @param lc handle to the local client (henceforth invalid)
1698  */
1699 void
1700 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1701 {
1702   if (NULL == cp_map)
1703     return; /* already cleaned up */
1704   GNUNET_CONTAINER_multihashmap_iterate (cp_map,
1705                                          &clean_local_client,
1706                                          (void*) lc);
1707 }
1708
1709
1710 /* end of gnunet-service-fs_cp.c */