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