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