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