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