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