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