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