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