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