small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[oweals/gnunet.git] / src / fs / gnunet-service-fs_cp.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file fs/gnunet-service-fs_cp.c
22  * @brief API to handle 'connected peers'
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.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 #include "gnunet_peerstore_service.h"
34
35
36 /**
37  * Ratio for moving average delay calculation.  The previous
38  * average goes in with a factor of (n-1) into the calculation.
39  * Must be > 0.
40  */
41 #define RUNAVG_DELAY_N 16
42
43 /**
44  * How often do we flush respect values to disk?
45  */
46 #define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
47
48 /**
49  * After how long do we discard a reply?
50  */
51 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
52
53 /**
54  * Collect an instane number of statistics?  May cause excessive IPC.
55  */
56 #define INSANE_STATISTICS GNUNET_NO
57
58
59 /**
60  * Handle to cancel a transmission request.
61  */
62 struct GSF_PeerTransmitHandle
63 {
64
65   /**
66    * Kept in a doubly-linked list.
67    */
68   struct GSF_PeerTransmitHandle *next;
69
70   /**
71    * Kept in a doubly-linked list.
72    */
73   struct GSF_PeerTransmitHandle *prev;
74
75   /**
76    * Time when this transmission request was issued.
77    */
78   struct GNUNET_TIME_Absolute transmission_request_start_time;
79
80   /**
81    * Timeout for this request.
82    */
83   struct GNUNET_TIME_Absolute timeout;
84
85   /**
86    * Task called on timeout, or 0 for none.
87    */
88   struct GNUNET_SCHEDULER_Task *timeout_task;
89
90   /**
91    * Function to call to get the actual message.
92    */
93   GSF_GetMessageCallback gmc;
94
95   /**
96    * Peer this request targets.
97    */
98   struct GSF_ConnectedPeer *cp;
99
100   /**
101    * Closure for @e gmc.
102    */
103   void *gmc_cls;
104
105   /**
106    * Size of the message to be transmitted.
107    */
108   size_t size;
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   struct GNUNET_SCHEDULER_Task *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 (generic: from peer or local client).
175    */
176   struct GSF_PendingRequest *pr;
177
178   /**
179    * Which specific peer issued this request?
180    */
181   struct GSF_ConnectedPeer *cp;
182
183   /**
184    * Task for asynchronous stopping of this request.
185    */
186   struct GNUNET_SCHEDULER_Task *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   struct GNUNET_SCHEDULER_Task *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_ATS_reserve_bandwidth call (or NULL).
244    */
245   struct GNUNET_ATS_ReservationContext *rc;
246
247   /**
248    * Task scheduled if we need to retry bandwidth reservation later.
249    */
250   struct GNUNET_SCHEDULER_Task *rc_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    * Handle for an active request for transmission to this
259    * peer, or NULL (if core queue was full).
260    */
261   struct GNUNET_CORE_TransmitHandle *cth;
262
263   /**
264    * Increase in traffic preference still to be submitted
265    * to the core service for this peer.
266    */
267   uint64_t inc_preference;
268
269   /**
270    * Set to 1 if we're currently in the process of calling
271    * #GNUNET_CORE_notify_transmit_ready() (so while @e cth is
272    * NULL, we should not call notify_transmit_ready for this
273    * handle right now).
274    */
275   unsigned int cth_in_progress;
276
277   /**
278    * Number of entries in @e delayed_head DLL.
279    */
280   unsigned int delay_queue_size;
281
282   /**
283    * Respect rating for this peer on disk.
284    */
285   uint32_t disk_respect;
286
287   /**
288    * Which offset in @e last_p2p_replies will be updated next?
289    * (we go round-robin).
290    */
291   unsigned int last_p2p_replies_woff;
292
293   /**
294    * Which offset in @e last_client_replies will be updated next?
295    * (we go round-robin).
296    */
297   unsigned int last_client_replies_woff;
298
299   /**
300    * Current offset into @e last_request_times ring buffer.
301    */
302   unsigned int last_request_times_off;
303
304   /**
305    * #GNUNET_YES if we did successfully reserve 32k bandwidth,
306    * #GNUNET_NO if not.
307    */
308   int did_reserve;
309
310   /**
311    * Function called when the creation of this record is complete.
312    */
313   GSF_ConnectedPeerCreationCallback creation_cb;
314
315   /**
316    * Closure for @e creation_cb
317    */
318   void *creation_cb_cls;
319
320   /**
321    * Handle to the PEERSTORE iterate request for peer respect value
322    */
323   struct GNUNET_PEERSTORE_IterateContext *respect_iterate_req;
324
325 };
326
327
328 /**
329  * Map from peer identities to `struct GSF_ConnectPeer` entries.
330  */
331 static struct GNUNET_CONTAINER_MultiPeerMap *cp_map;
332
333 /**
334  * Handle to peerstore service.
335  */
336 static struct GNUNET_PEERSTORE_Handle *peerstore;
337
338
339 /**
340  * Update the latency information kept for the given peer.
341  *
342  * @param id peer record to update
343  * @param latency current latency value
344  */
345 void
346 GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id,
347                           struct GNUNET_TIME_Relative latency)
348 {
349   struct GSF_ConnectedPeer *cp;
350
351   cp = GSF_peer_get_ (id);
352   if (NULL == cp)
353     return; /* we're not yet connected at the core level, ignore */
354   GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay,
355                                  latency);
356 }
357
358
359 /**
360  * Return the performance data record for the given peer
361  *
362  * @param cp peer to query
363  * @return performance data record for the peer
364  */
365 struct GSF_PeerPerformanceData *
366 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
367 {
368   return &cp->ppd;
369 }
370
371
372 /**
373  * Core is ready to transmit to a peer, get the message.
374  *
375  * @param cls the `struct GSF_PeerTransmitHandle` of the message
376  * @param size number of bytes core is willing to take
377  * @param buf where to copy the message
378  * @return number of bytes copied to @a buf
379  */
380 static size_t
381 peer_transmit_ready_cb (void *cls,
382                         size_t size,
383                         void *buf);
384
385
386 /**
387  * Function called by core upon success or failure of our bandwidth reservation request.
388  *
389  * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
390  * @param peer identifies the peer
391  * @param amount set to the amount that was actually reserved or unreserved;
392  *               either the full requested amount or zero (no partial reservations)
393  * @param res_delay if the reservation could not be satisfied (amount was 0), how
394  *        long should the client wait until re-trying?
395  */
396 static void
397 ats_reserve_callback (void *cls,
398                       const struct GNUNET_PeerIdentity *peer,
399                       int32_t amount,
400                       struct GNUNET_TIME_Relative res_delay);
401
402
403 /**
404  * If ready (bandwidth reserved), try to schedule transmission via
405  * core for the given handle.
406  *
407  * @param pth transmission handle to schedule
408  */
409 static void
410 schedule_transmission (struct GSF_PeerTransmitHandle *pth)
411 {
412   struct GSF_ConnectedPeer *cp;
413   struct GNUNET_PeerIdentity target;
414
415   cp = pth->cp;
416   if ((NULL != cp->cth) || (0 != cp->cth_in_progress))
417     return;                     /* already done */
418   GNUNET_assert (0 != cp->ppd.pid);
419   GNUNET_PEER_resolve (cp->ppd.pid, &target);
420
421   if (0 != cp->inc_preference)
422   {
423     GNUNET_ATS_performance_change_preference (GSF_ats,
424                                               &target,
425                                               GNUNET_ATS_PREFERENCE_BANDWIDTH,
426                                               (double) cp->inc_preference,
427                                               GNUNET_ATS_PREFERENCE_END);
428     cp->inc_preference = 0;
429   }
430
431   if ( (GNUNET_YES == pth->is_query) &&
432        (GNUNET_YES != pth->was_reserved) )
433   {
434     /* query, need reservation */
435     if (GNUNET_YES != cp->did_reserve)
436       return;                   /* not ready */
437     cp->did_reserve = GNUNET_NO;
438     /* reservation already done! */
439     pth->was_reserved = GNUNET_YES;
440     cp->rc = GNUNET_ATS_reserve_bandwidth (GSF_ats,
441                                            &target,
442                                            DBLOCK_SIZE,
443                                            &ats_reserve_callback,
444                                            cp);
445     return;
446   }
447   GNUNET_assert (NULL == cp->cth);
448   cp->cth_in_progress++;
449   cp->cth =
450     GNUNET_CORE_notify_transmit_ready (GSF_core,
451                                        GNUNET_YES,
452                                        GNUNET_CORE_PRIO_BACKGROUND,
453                                        GNUNET_TIME_absolute_get_remaining (pth->timeout),
454                                        &target,
455                                        pth->size,
456                                        &peer_transmit_ready_cb, cp);
457   GNUNET_assert (NULL != cp->cth);
458   GNUNET_assert (0 < cp->cth_in_progress--);
459 }
460
461
462 /**
463  * Core is ready to transmit to a peer, get the message.
464  *
465  * @param cls the `struct GSF_PeerTransmitHandle` of the message
466  * @param size number of bytes core is willing to take
467  * @param buf where to copy the message
468  * @return number of bytes copied to @a buf
469  */
470 static size_t
471 peer_transmit_ready_cb (void *cls,
472                         size_t size,
473                         void *buf)
474 {
475   struct GSF_ConnectedPeer *cp = cls;
476   struct GSF_PeerTransmitHandle *pth = cp->pth_head;
477   struct GSF_PeerTransmitHandle *pos;
478   size_t ret;
479
480   cp->cth = NULL;
481   if (NULL == pth)
482     return 0;
483   if (pth->size > size)
484   {
485     schedule_transmission (pth);
486     return 0;
487   }
488   if (NULL != pth->timeout_task)
489   {
490     GNUNET_SCHEDULER_cancel (pth->timeout_task);
491     pth->timeout_task = NULL;
492   }
493   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
494                                cp->pth_tail,
495                                pth);
496   if (GNUNET_YES == pth->is_query)
497   {
498     cp->ppd.last_request_times[(cp->last_request_times_off++) %
499                                MAX_QUEUE_PER_PEER] =
500       GNUNET_TIME_absolute_get ();
501     GNUNET_assert (0 < cp->ppd.pending_queries--);
502   }
503   else if (GNUNET_NO == pth->is_query)
504   {
505     GNUNET_assert (0 < cp->ppd.pending_replies--);
506   }
507   GNUNET_LOAD_update (cp->ppd.transmission_delay,
508                       GNUNET_TIME_absolute_get_duration
509                       (pth->transmission_request_start_time).rel_value_us);
510   ret = pth->gmc (pth->gmc_cls, size, buf);
511   if (NULL != (pos = cp->pth_head))
512   {
513     GNUNET_assert (pos != pth);
514     schedule_transmission (pos);
515   }
516   GNUNET_free (pth);
517   return ret;
518 }
519
520
521 /**
522  * (re)try to reserve bandwidth from the given peer.
523  *
524  * @param cls the `struct GSF_ConnectedPeer` to reserve from
525  */
526 static void
527 retry_reservation (void *cls)
528 {
529   struct GSF_ConnectedPeer *cp = cls;
530   struct GNUNET_PeerIdentity target;
531
532   GNUNET_PEER_resolve (cp->ppd.pid, &target);
533   cp->rc_delay_task = NULL;
534   cp->rc =
535     GNUNET_ATS_reserve_bandwidth (GSF_ats,
536                                   &target,
537                                   DBLOCK_SIZE,
538                                   &ats_reserve_callback, cp);
539 }
540
541
542 /**
543  * Function called by core upon success or failure of our bandwidth reservation request.
544  *
545  * @param cls the `struct GSF_ConnectedPeer` of the peer for which we made the request
546  * @param peer identifies the peer
547  * @param amount set to the amount that was actually reserved or unreserved;
548  *               either the full requested amount or zero (no partial reservations)
549  * @param res_delay if the reservation could not be satisfied (amount was 0), how
550  *        long should the client wait until re-trying?
551  */
552 static void
553 ats_reserve_callback (void *cls,
554                       const struct GNUNET_PeerIdentity *peer,
555                       int32_t amount,
556                       struct GNUNET_TIME_Relative res_delay)
557 {
558   struct GSF_ConnectedPeer *cp = cls;
559   struct GSF_PeerTransmitHandle *pth;
560
561   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
562               "Reserved %d bytes / need to wait %s for reservation\n",
563               (int) amount,
564               GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES));
565   cp->rc = NULL;
566   if (0 == amount)
567   {
568     cp->rc_delay_task =
569         GNUNET_SCHEDULER_add_delayed (res_delay,
570                                       &retry_reservation,
571                                       cp);
572     return;
573   }
574   cp->did_reserve = GNUNET_YES;
575   pth = cp->pth_head;
576   if ( (NULL != pth) &&
577        (NULL == cp->cth) &&
578        (0 == cp->cth_in_progress) )
579   {
580     /* reservation success, try transmission now! */
581     cp->cth_in_progress++;
582     cp->cth =
583         GNUNET_CORE_notify_transmit_ready (GSF_core,
584                                            GNUNET_YES,
585                                            GNUNET_CORE_PRIO_BACKGROUND,
586                                            GNUNET_TIME_absolute_get_remaining (pth->timeout),
587                                            peer,
588                                            pth->size,
589                                            &peer_transmit_ready_cb,
590                                            cp);
591     GNUNET_assert (NULL != cp->cth);
592     GNUNET_assert (0 < cp->cth_in_progress--);
593   }
594 }
595
596
597 /**
598  * Function called by PEERSTORE with peer respect record
599  *
600  * @param cls handle to connected peer entry
601  * @param record peerstore record information
602  * @param emsg error message, or NULL if no errors
603  * @return #GNUNET_NO to stop iterating since we only expect 0 or 1 records
604  */
605 static int
606 peer_respect_cb (void *cls,
607                  const struct GNUNET_PEERSTORE_Record *record,
608                  const char *emsg)
609 {
610   struct GSF_ConnectedPeer *cp = cls;
611
612   GNUNET_assert (NULL != cp->respect_iterate_req);
613   cp->respect_iterate_req = NULL;
614   if ((NULL != record) && (sizeof (cp->disk_respect) == record->value_size))
615     cp->disk_respect = cp->ppd.respect = *((uint32_t *)record->value);
616   GSF_push_start_ (cp);
617   if (NULL != cp->creation_cb)
618     cp->creation_cb (cp->creation_cb_cls, cp);
619   return GNUNET_NO;
620 }
621
622
623 /**
624  * A peer connected to us.  Setup the connected peer
625  * records.
626  *
627  * @param peer identity of peer that connected
628  * @param creation_cb callback function when the record is created.
629  * @param creation_cb_cls closure for @creation_cb
630  */
631 void
632 GSF_peer_connect_handler_ (const struct GNUNET_PeerIdentity *peer,
633                            GSF_ConnectedPeerCreationCallback creation_cb,
634                            void *creation_cb_cls)
635 {
636   struct GSF_ConnectedPeer *cp;
637
638   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
639               "Connected to peer %s\n",
640               GNUNET_i2s (peer));
641   cp = GNUNET_new (struct GSF_ConnectedPeer);
642   cp->ppd.pid = GNUNET_PEER_intern (peer);
643   cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO);
644   cp->rc =
645       GNUNET_ATS_reserve_bandwidth (GSF_ats,
646                                     peer,
647                                     DBLOCK_SIZE,
648                                     &ats_reserve_callback, cp);
649   cp->request_map = GNUNET_CONTAINER_multihashmap_create (128,
650                                                           GNUNET_YES);
651   GNUNET_break (GNUNET_OK ==
652                 GNUNET_CONTAINER_multipeermap_put (cp_map,
653                GSF_connected_peer_get_identity2_ (cp),
654                                                    cp,
655                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
656   GNUNET_STATISTICS_set (GSF_stats,
657                          gettext_noop ("# peers connected"),
658                          GNUNET_CONTAINER_multipeermap_size (cp_map),
659                          GNUNET_NO);
660   cp->creation_cb = creation_cb;
661   cp->creation_cb_cls = creation_cb_cls;
662   cp->respect_iterate_req =
663       GNUNET_PEERSTORE_iterate (peerstore, "fs",
664                                 peer, "respect",
665                                 GNUNET_TIME_UNIT_FOREVER_REL,
666                                 &peer_respect_cb,
667                                 cp);
668 }
669
670
671 /**
672  * It may be time to re-start migrating content to this
673  * peer.  Check, and if so, restart migration.
674  *
675  * @param cls the `struct GSF_ConnectedPeer`
676  */
677 static void
678 revive_migration (void *cls)
679 {
680   struct GSF_ConnectedPeer *cp = cls;
681   struct GNUNET_TIME_Relative bt;
682
683   cp->mig_revive_task = NULL;
684   bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until);
685   if (0 != bt.rel_value_us)
686   {
687     /* still time left... */
688     cp->mig_revive_task =
689         GNUNET_SCHEDULER_add_delayed (bt, &revive_migration, cp);
690     return;
691   }
692   GSF_push_start_ (cp);
693 }
694
695
696 /**
697  * Get a handle for a connected peer.
698  *
699  * @param peer peer's identity
700  * @return NULL if the peer is not currently connected
701  */
702 struct GSF_ConnectedPeer *
703 GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer)
704 {
705   if (NULL == cp_map)
706     return NULL;
707   return GNUNET_CONTAINER_multipeermap_get (cp_map, peer);
708 }
709
710
711 /**
712  * Handle P2P "MIGRATION_STOP" message.
713  *
714  * @param cls closure, always NULL
715  * @param other the other peer involved (sender or receiver, NULL
716  *        for loopback messages where we are both sender and receiver)
717  * @param message the actual message
718  * @return #GNUNET_OK to keep the connection open,
719  *         #GNUNET_SYSERR to close it (signal serious error)
720  */
721 int
722 GSF_handle_p2p_migration_stop_ (void *cls,
723                                 const struct GNUNET_PeerIdentity *other,
724                                 const struct GNUNET_MessageHeader *message)
725 {
726   struct GSF_ConnectedPeer *cp;
727   const struct MigrationStopMessage *msm;
728   struct GNUNET_TIME_Relative bt;
729
730   msm = (const struct MigrationStopMessage *) message;
731   cp = GSF_peer_get_ (other);
732   if (NULL == cp)
733   {
734     GNUNET_break (0);
735     return GNUNET_OK;
736   }
737   GNUNET_STATISTICS_update (GSF_stats,
738                             gettext_noop ("# migration stop messages received"),
739                             1, GNUNET_NO);
740   bt = GNUNET_TIME_relative_ntoh (msm->duration);
741   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
742               _("Migration of content to peer `%s' blocked for %s\n"),
743               GNUNET_i2s (other),
744               GNUNET_STRINGS_relative_time_to_string (bt, GNUNET_YES));
745   cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt);
746   if ( (NULL == cp->mig_revive_task) &&
747        (NULL == cp->respect_iterate_req) )
748   {
749     GSF_push_stop_ (cp);
750     cp->mig_revive_task =
751         GNUNET_SCHEDULER_add_delayed (bt,
752                                       &revive_migration, cp);
753   }
754   return GNUNET_OK;
755 }
756
757
758 /**
759  * Copy reply and free put message.
760  *
761  * @param cls the `struct PutMessage`
762  * @param buf_size number of bytes available in @a buf
763  * @param buf where to copy the message, NULL on error (peer disconnect)
764  * @return number of bytes copied to @a buf, can be 0 (without indicating an error)
765  */
766 static size_t
767 copy_reply (void *cls,
768             size_t buf_size,
769             void *buf)
770 {
771   struct PutMessage *pm = cls;
772   size_t size;
773
774   if (NULL != buf)
775   {
776     GNUNET_assert (buf_size >= ntohs (pm->header.size));
777     size = ntohs (pm->header.size);
778     memcpy (buf, pm, size);
779     GNUNET_STATISTICS_update (GSF_stats,
780                               gettext_noop ("# replies transmitted to other peers"),
781                               1,
782                               GNUNET_NO);
783   }
784   else
785   {
786     size = 0;
787     GNUNET_STATISTICS_update (GSF_stats,
788                               gettext_noop ("# replies dropped"),
789                               1,
790                               GNUNET_NO);
791   }
792   GNUNET_free (pm);
793   return size;
794 }
795
796
797 /**
798  * Free resources associated with the given peer request.
799  *
800  * @param peerreq request to free
801  */
802 static void
803 free_pending_request (struct PeerRequest *peerreq)
804 {
805   struct GSF_ConnectedPeer *cp = peerreq->cp;
806   struct GSF_PendingRequestData *prd;
807
808   prd = GSF_pending_request_get_data_ (peerreq->pr);
809   if (NULL != peerreq->kill_task)
810   {
811     GNUNET_SCHEDULER_cancel (peerreq->kill_task);
812     peerreq->kill_task = NULL;
813   }
814   GNUNET_STATISTICS_update (GSF_stats,
815                             gettext_noop ("# P2P searches active"),
816                             -1,
817                             GNUNET_NO);
818   GNUNET_break (GNUNET_YES ==
819                 GNUNET_CONTAINER_multihashmap_remove (cp->request_map,
820                                                       &prd->query,
821                                                       peerreq));
822   GNUNET_free (peerreq);
823 }
824
825
826 /**
827  * Cancel all requests associated with the peer.
828  *
829  * @param cls unused
830  * @param query hash code of the request
831  * @param value the `struct GSF_PendingRequest`
832  * @return #GNUNET_YES (continue to iterate)
833  */
834 static int
835 cancel_pending_request (void *cls,
836                         const struct GNUNET_HashCode *query,
837                         void *value)
838 {
839   struct PeerRequest *peerreq = value;
840   struct GSF_PendingRequest *pr = peerreq->pr;
841
842   free_pending_request (peerreq);
843   GSF_pending_request_cancel_ (pr,
844                                GNUNET_NO);
845   return GNUNET_OK;
846 }
847
848
849 /**
850  * Free the given request.
851  *
852  * @param cls the request to free
853  */
854 static void
855 peer_request_destroy (void *cls)
856 {
857   struct PeerRequest *peerreq = cls;
858   struct GSF_PendingRequest *pr = peerreq->pr;
859   struct GSF_PendingRequestData *prd;
860
861   peerreq->kill_task = NULL;
862   prd = GSF_pending_request_get_data_ (pr);
863   cancel_pending_request (NULL,
864                           &prd->query,
865                           peerreq);
866 }
867
868
869 /**
870  * The artificial delay is over, transmit the message now.
871  *
872  * @param cls the `struct GSF_DelayedHandle` with the message
873  */
874 static void
875 transmit_delayed_now (void *cls)
876 {
877   struct GSF_DelayedHandle *dh = cls;
878   struct GSF_ConnectedPeer *cp = dh->cp;
879   const struct GNUNET_SCHEDULER_TaskContext *tc;
880
881   GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
882                                cp->delayed_tail,
883                                dh);
884   cp->delay_queue_size--;
885   tc = GNUNET_SCHEDULER_get_task_context ();
886   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
887   {
888     GNUNET_free (dh->pm);
889     GNUNET_free (dh);
890     return;
891   }
892   (void) GSF_peer_transmit_ (cp,
893                              GNUNET_NO,
894                              UINT32_MAX,
895                              REPLY_TIMEOUT,
896                              dh->msize,
897                              &copy_reply,
898                              dh->pm);
899   GNUNET_free (dh);
900 }
901
902
903 /**
904  * Get the randomized delay a response should be subjected to.
905  *
906  * @return desired delay
907  */
908 static struct GNUNET_TIME_Relative
909 get_randomized_delay ()
910 {
911   struct GNUNET_TIME_Relative ret;
912
913   ret =
914       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
915                                      GNUNET_CRYPTO_random_u32
916                                      (GNUNET_CRYPTO_QUALITY_WEAK,
917                                       2 * GSF_avg_latency.rel_value_us + 1));
918 #if INSANE_STATISTICS
919   GNUNET_STATISTICS_update (GSF_stats,
920                             gettext_noop
921                             ("# artificial delays introduced (ms)"),
922                             ret.rel_value_us / 1000LL, GNUNET_NO);
923 #endif
924   return ret;
925 }
926
927
928 /**
929  * Handle a reply to a pending request.  Also called if a request
930  * expires (then with data == NULL).  The handler may be called
931  * many times (depending on the request type), but will not be
932  * called during or after a call to GSF_pending_request_cancel
933  * and will also not be called anymore after a call signalling
934  * expiration.
935  *
936  * @param cls `struct PeerRequest` this is an answer for
937  * @param eval evaluation of the result
938  * @param pr handle to the original pending request
939  * @param reply_anonymity_level anonymity level for the reply, UINT32_MAX for "unknown"
940  * @param expiration when does @a data expire?
941  * @param last_transmission when did we last transmit a request for this block
942  * @param type type of the block
943  * @param data response data, NULL on request expiration
944  * @param data_len number of bytes in @a data
945  */
946 static void
947 handle_p2p_reply (void *cls,
948                   enum GNUNET_BLOCK_EvaluationResult eval,
949                   struct GSF_PendingRequest *pr,
950                   uint32_t reply_anonymity_level,
951                   struct GNUNET_TIME_Absolute expiration,
952                   struct GNUNET_TIME_Absolute last_transmission,
953                   enum GNUNET_BLOCK_Type type,
954                   const void *data,
955                   size_t data_len)
956 {
957   struct PeerRequest *peerreq = cls;
958   struct GSF_ConnectedPeer *cp = peerreq->cp;
959   struct GSF_PendingRequestData *prd;
960   struct PutMessage *pm;
961   size_t msize;
962
963   GNUNET_assert (data_len + sizeof (struct PutMessage) <
964                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
965   GNUNET_assert (peerreq->pr == pr);
966   prd = GSF_pending_request_get_data_ (pr);
967   if (NULL == data)
968   {
969     free_pending_request (peerreq);
970     return;
971   }
972   GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type);
973   if ((prd->type != type) && (GNUNET_BLOCK_TYPE_ANY != prd->type))
974   {
975     GNUNET_STATISTICS_update (GSF_stats,
976                               gettext_noop
977                               ("# replies dropped due to type mismatch"),
978                                 1, GNUNET_NO);
979     return;
980   }
981   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982               "Transmitting result for query `%s' to peer\n",
983               GNUNET_h2s (&prd->query));
984   GNUNET_STATISTICS_update (GSF_stats,
985                             gettext_noop ("# replies received for other peers"),
986                             1, GNUNET_NO);
987   msize = sizeof (struct PutMessage) + data_len;
988   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
989   {
990     GNUNET_break (0);
991     return;
992   }
993   if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1))
994   {
995     if (reply_anonymity_level - 1 > GSF_cover_content_count)
996     {
997       GNUNET_STATISTICS_update (GSF_stats,
998                                 gettext_noop
999                                 ("# replies dropped due to insufficient cover traffic"),
1000                                 1, GNUNET_NO);
1001       return;
1002     }
1003     GSF_cover_content_count -= (reply_anonymity_level - 1);
1004   }
1005
1006   pm = GNUNET_malloc (msize);
1007   pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1008   pm->header.size = htons (msize);
1009   pm->type = htonl (type);
1010   pm->expiration = GNUNET_TIME_absolute_hton (expiration);
1011   memcpy (&pm[1], data, data_len);
1012   if ( (UINT32_MAX != reply_anonymity_level) &&
1013        (0 != reply_anonymity_level) &&
1014        (GNUNET_YES == GSF_enable_randomized_delays) )
1015   {
1016     struct GSF_DelayedHandle *dh;
1017
1018     dh = GNUNET_new (struct GSF_DelayedHandle);
1019     dh->cp = cp;
1020     dh->pm = pm;
1021     dh->msize = msize;
1022     GNUNET_CONTAINER_DLL_insert (cp->delayed_head,
1023                                  cp->delayed_tail,
1024                                  dh);
1025     cp->delay_queue_size++;
1026     dh->delay_task =
1027         GNUNET_SCHEDULER_add_delayed (get_randomized_delay (),
1028                                       &transmit_delayed_now,
1029                                       dh);
1030   }
1031   else
1032   {
1033     (void) GSF_peer_transmit_ (cp,
1034                                GNUNET_NO,
1035                                UINT32_MAX,
1036                                REPLY_TIMEOUT,
1037                                msize,
1038                                &copy_reply,
1039                                pm);
1040   }
1041   if (GNUNET_BLOCK_EVALUATION_OK_LAST != eval)
1042     return;
1043   if (NULL == peerreq->kill_task)
1044   {
1045     GNUNET_STATISTICS_update (GSF_stats,
1046                               gettext_noop
1047                               ("# P2P searches destroyed due to ultimate reply"),
1048                               1,
1049                               GNUNET_NO);
1050     peerreq->kill_task =
1051         GNUNET_SCHEDULER_add_now (&peer_request_destroy,
1052                                   peerreq);
1053   }
1054 }
1055
1056
1057 /**
1058  * Increase the peer's respect by a value.
1059  *
1060  * @param cp which peer to change the respect value on
1061  * @param value is the int value by which the
1062  *  peer's credit is to be increased or decreased
1063  * @returns the actual change in respect (positive or negative)
1064  */
1065 static int
1066 change_peer_respect (struct GSF_ConnectedPeer *cp, int value)
1067 {
1068   if (0 == value)
1069     return 0;
1070   GNUNET_assert (NULL != cp);
1071   if (value > 0)
1072   {
1073     if (cp->ppd.respect + value < cp->ppd.respect)
1074     {
1075       value = UINT32_MAX - cp->ppd.respect;
1076       cp->ppd.respect = UINT32_MAX;
1077     }
1078     else
1079       cp->ppd.respect += value;
1080   }
1081   else
1082   {
1083     if (cp->ppd.respect < -value)
1084     {
1085       value = -cp->ppd.respect;
1086       cp->ppd.respect = 0;
1087     }
1088     else
1089       cp->ppd.respect += value;
1090   }
1091   return value;
1092 }
1093
1094
1095 /**
1096  * We've received a request with the specified priority.  Bound it
1097  * according to how much we respect the given peer.
1098  *
1099  * @param prio_in requested priority
1100  * @param cp the peer making the request
1101  * @return effective priority
1102  */
1103 static int32_t
1104 bound_priority (uint32_t prio_in,
1105                 struct GSF_ConnectedPeer *cp)
1106 {
1107 #define N ((double)128.0)
1108   uint32_t ret;
1109   double rret;
1110   int ld;
1111
1112   ld = GSF_test_get_load_too_high_ (0);
1113   if (GNUNET_SYSERR == ld)
1114   {
1115 #if INSANE_STATISTICS
1116     GNUNET_STATISTICS_update (GSF_stats,
1117                               gettext_noop
1118                               ("# requests done for free (low load)"), 1,
1119                               GNUNET_NO);
1120 #endif
1121     return 0;                   /* excess resources */
1122   }
1123   if (prio_in > INT32_MAX)
1124     prio_in = INT32_MAX;
1125   ret = -change_peer_respect (cp, -(int) prio_in);
1126   if (ret > 0)
1127   {
1128     if (ret > GSF_current_priorities + N)
1129       rret = GSF_current_priorities + N;
1130     else
1131       rret = ret;
1132     GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N;
1133   }
1134   if ((GNUNET_YES == ld) && (ret > 0))
1135   {
1136     /* try with charging */
1137     ld = GSF_test_get_load_too_high_ (ret);
1138   }
1139   if (GNUNET_YES == ld)
1140   {
1141     GNUNET_STATISTICS_update (GSF_stats,
1142                               gettext_noop
1143                               ("# request dropped, priority insufficient"), 1,
1144                               GNUNET_NO);
1145     /* undo charge */
1146     change_peer_respect (cp, (int) ret);
1147     return -1;                  /* not enough resources */
1148   }
1149   else
1150   {
1151     GNUNET_STATISTICS_update (GSF_stats,
1152                               gettext_noop
1153                               ("# requests done for a price (normal load)"), 1,
1154                               GNUNET_NO);
1155   }
1156 #undef N
1157   return ret;
1158 }
1159
1160
1161 /**
1162  * The priority level imposes a bound on the maximum
1163  * value for the ttl that can be requested.
1164  *
1165  * @param ttl_in requested ttl
1166  * @param prio given priority
1167  * @return @a ttl_in if @a ttl_in is below the limit,
1168  *         otherwise the ttl-limit for the given @a prio
1169  */
1170 static int32_t
1171 bound_ttl (int32_t ttl_in,
1172            uint32_t prio)
1173 {
1174   unsigned long long allowed;
1175
1176   if (ttl_in <= 0)
1177     return ttl_in;
1178   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
1179   if (ttl_in > allowed)
1180   {
1181     if (allowed >= (1 << 30))
1182       return 1 << 30;
1183     return allowed;
1184   }
1185   return ttl_in;
1186 }
1187
1188
1189 /**
1190  * Closure for #test_exist_cb().
1191  */
1192 struct TestExistClosure
1193 {
1194
1195   /**
1196    * Priority of the incoming request.
1197    */
1198   int32_t priority;
1199
1200   /**
1201    * Relative TTL of the incoming request.
1202    */
1203   int32_t ttl;
1204
1205   /**
1206    * Type of the incoming request.
1207    */
1208   enum GNUNET_BLOCK_Type type;
1209
1210   /**
1211    * Set to #GNUNET_YES if we are done handling the query.
1212    */
1213   int finished;
1214
1215 };
1216
1217
1218 /**
1219  * Test if the query already exists.  If so, merge it, otherwise
1220  * keep `finished` at #GNUNET_NO.
1221  *
1222  * @param cls our `struct TestExistClosure`
1223  * @param hc the key of the query
1224  * @param value the existing `struct PeerRequest`.
1225  * @return #GNUNET_YES to continue to iterate,
1226  *         #GNUNET_NO if we successfully merged
1227  */
1228 static int
1229 test_exist_cb (void *cls,
1230                const struct GNUNET_HashCode *hc,
1231                void *value)
1232 {
1233   struct TestExistClosure *tec = cls;
1234   struct PeerRequest *peerreq = value;
1235   struct GSF_PendingRequest *pr;
1236   struct GSF_PendingRequestData *prd;
1237
1238   pr = peerreq->pr;
1239   prd = GSF_pending_request_get_data_ (pr);
1240   if (prd->type != tec->type)
1241     return GNUNET_YES;
1242   if (prd->ttl.abs_value_us >=
1243       GNUNET_TIME_absolute_get ().abs_value_us + tec->ttl * 1000LL)
1244   {
1245     /* existing request has higher TTL, drop new one! */
1246     prd->priority += tec->priority;
1247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248                 "Have existing request with higher TTL, dropping new request.\n");
1249     GNUNET_STATISTICS_update (GSF_stats,
1250                               gettext_noop
1251                               ("# requests dropped due to higher-TTL request"),
1252                               1, GNUNET_NO);
1253     tec->finished = GNUNET_YES;
1254     return GNUNET_NO;
1255   }
1256   /* existing request has lower TTL, drop old one! */
1257   tec->priority += prd->priority;
1258   free_pending_request (peerreq);
1259   GSF_pending_request_cancel_ (pr,
1260                                GNUNET_YES);
1261   return GNUNET_NO;
1262 }
1263
1264
1265 /**
1266  * Handle P2P "QUERY" message.  Creates the pending request entry
1267  * and sets up all of the data structures to that we will
1268  * process replies properly.  Does not initiate forwarding or
1269  * local database lookups.
1270  *
1271  * @param other the other peer involved (sender or receiver, NULL
1272  *        for loopback messages where we are both sender and receiver)
1273  * @param message the actual message
1274  * @return pending request handle, NULL on error
1275  */
1276 struct GSF_PendingRequest *
1277 GSF_handle_p2p_query_ (const struct GNUNET_PeerIdentity *other,
1278                        const struct GNUNET_MessageHeader *message)
1279 {
1280   struct PeerRequest *peerreq;
1281   struct GSF_PendingRequest *pr;
1282   struct GSF_ConnectedPeer *cp;
1283   struct GSF_ConnectedPeer *cps;
1284   const struct GNUNET_PeerIdentity *target;
1285   enum GSF_PendingRequestOptions options;
1286   uint16_t msize;
1287   const struct GetMessage *gm;
1288   unsigned int bits;
1289   const struct GNUNET_PeerIdentity *opt;
1290   uint32_t bm;
1291   size_t bfsize;
1292   uint32_t ttl_decrement;
1293   struct TestExistClosure tec;
1294   GNUNET_PEER_Id spid;
1295   const struct GSF_PendingRequestData *prd;
1296
1297   msize = ntohs (message->size);
1298   if (msize < sizeof (struct GetMessage))
1299   {
1300     GNUNET_break_op (0);
1301     return NULL;
1302   }
1303   GNUNET_STATISTICS_update (GSF_stats,
1304                             gettext_noop
1305                             ("# GET requests received (from other peers)"),
1306                             1,
1307                             GNUNET_NO);
1308   gm = (const struct GetMessage *) message;
1309   tec.type = ntohl (gm->type);
1310   bm = ntohl (gm->hash_bitmap);
1311   bits = 0;
1312   while (bm > 0)
1313   {
1314     if (1 == (bm & 1))
1315       bits++;
1316     bm >>= 1;
1317   }
1318   if (msize < sizeof (struct GetMessage) + bits * sizeof (struct GNUNET_PeerIdentity))
1319   {
1320     GNUNET_break_op (0);
1321     return NULL;
1322   }
1323   opt = (const struct GNUNET_PeerIdentity *) &gm[1];
1324   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (struct GNUNET_PeerIdentity);
1325   /* bfsize must be power of 2, check! */
1326   if (0 != ((bfsize - 1) & bfsize))
1327   {
1328     GNUNET_break_op (0);
1329     return NULL;
1330   }
1331   GSF_cover_query_count++;
1332   bm = ntohl (gm->hash_bitmap);
1333   bits = 0;
1334   cps = GSF_peer_get_ (other);
1335   if (NULL == cps)
1336   {
1337     /* peer must have just disconnected */
1338     GNUNET_STATISTICS_update (GSF_stats,
1339                               gettext_noop
1340                               ("# requests dropped due to initiator not being connected"),
1341                               1, GNUNET_NO);
1342     return NULL;
1343   }
1344   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1345     cp = GSF_peer_get_ (&opt[bits++]);
1346   else
1347     cp = cps;
1348   if (NULL == cp)
1349   {
1350     if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
1351       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1352                   "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n",
1353                   GNUNET_i2s (&opt[bits - 1]));
1354
1355     else
1356       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1357                   "Failed to find peer `%s' in connection set. Dropping query.\n",
1358                   GNUNET_i2s (other));
1359     GNUNET_STATISTICS_update (GSF_stats,
1360                               gettext_noop
1361                               ("# requests dropped due to missing reverse route"),
1362                               1,
1363                               GNUNET_NO);
1364     return NULL;
1365   }
1366   if (cp->ppd.pending_replies + cp->delay_queue_size > MAX_QUEUE_PER_PEER)
1367   {
1368     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1369                 "Peer `%s' has too many replies queued already. Dropping query.\n",
1370                 GNUNET_i2s (other));
1371     GNUNET_STATISTICS_update (GSF_stats,
1372                               gettext_noop ("# requests dropped due to full reply queue"),
1373                               1,
1374                               GNUNET_NO);
1375     return NULL;
1376   }
1377   /* note that we can really only check load here since otherwise
1378    * peers could find out that we are overloaded by not being
1379    * disconnected after sending us a malformed query... */
1380   tec.priority = bound_priority (ntohl (gm->priority),
1381                                  cps);
1382   if (tec.priority < 0)
1383   {
1384     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1385                 "Dropping query from `%s', this peer is too busy.\n",
1386                 GNUNET_i2s (other));
1387     return NULL;
1388   }
1389   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1390               "Received request for `%s' of type %u from peer `%s' with flags %u\n",
1391               GNUNET_h2s (&gm->query),
1392               (unsigned int) tec.type,
1393               GNUNET_i2s (other),
1394               (unsigned int) bm);
1395   target =
1396       (0 !=
1397        (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? (&opt[bits++]) : NULL;
1398   options = GSF_PRO_DEFAULTS;
1399   spid = 0;
1400   if ((GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + tec.priority))
1401       || (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) >
1402           GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value_us * 2 +
1403           GNUNET_LOAD_get_average (GSF_rt_entry_lifetime)))
1404   {
1405     /* don't have BW to send to peer, or would likely take longer than we have for it,
1406      * so at best indirect the query */
1407     tec.priority = 0;
1408     options |= GSF_PRO_FORWARD_ONLY;
1409     spid = GNUNET_PEER_intern (other);
1410     GNUNET_assert (0 != spid);
1411   }
1412   tec.ttl = bound_ttl (ntohl (gm->ttl),
1413                        tec.priority);
1414   /* decrement ttl (always) */
1415   ttl_decrement =
1416       2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1417                                                     TTL_DECREMENT);
1418   if ((tec.ttl < 0) && (((int32_t) (tec.ttl - ttl_decrement)) > 0))
1419   {
1420     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421                 "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
1422                 GNUNET_i2s (other),
1423                 tec.ttl,
1424                 ttl_decrement);
1425     GNUNET_STATISTICS_update (GSF_stats,
1426                               gettext_noop
1427                               ("# requests dropped due TTL underflow"), 1,
1428                               GNUNET_NO);
1429     /* integer underflow => drop (should be very rare)! */
1430     return NULL;
1431   }
1432   tec.ttl -= ttl_decrement;
1433
1434   /* test if the request already exists */
1435   tec.finished = GNUNET_NO;
1436   GNUNET_CONTAINER_multihashmap_get_multiple (cp->request_map,
1437                                               &gm->query,
1438                                               &test_exist_cb,
1439                                               &tec);
1440   if (GNUNET_YES == tec.finished)
1441     return NULL; /* merged into existing request, we're done */
1442
1443   peerreq = GNUNET_new (struct PeerRequest);
1444   peerreq->cp = cp;
1445   pr = GSF_pending_request_create_ (options,
1446                                     tec.type,
1447                                     &gm->query,
1448                                     target,
1449                                     (bfsize > 0)
1450                                     ? (const char *) &opt[bits]
1451                                     : NULL,
1452                                     bfsize,
1453                                     ntohl (gm->filter_mutator),
1454                                     1 /* anonymity */,
1455                                     (uint32_t) tec.priority,
1456                                     tec.ttl,
1457                                     spid,
1458                                     GNUNET_PEER_intern (other),
1459                                     NULL, 0,        /* replies_seen */
1460                                     &handle_p2p_reply,
1461                                     peerreq);
1462   GNUNET_assert (NULL != pr);
1463   prd = GSF_pending_request_get_data_ (pr);
1464   peerreq->pr = pr;
1465   GNUNET_break (GNUNET_OK ==
1466                 GNUNET_CONTAINER_multihashmap_put (cp->request_map,
1467                                                    &prd->query,
1468                                                    peerreq,
1469                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1470   GNUNET_STATISTICS_update (GSF_stats,
1471                             gettext_noop ("# P2P query messages received and processed"),
1472                             1,
1473                             GNUNET_NO);
1474   GNUNET_STATISTICS_update (GSF_stats,
1475                             gettext_noop ("# P2P searches active"),
1476                             1,
1477                             GNUNET_NO);
1478   return pr;
1479 }
1480
1481
1482 /**
1483  * Function called if there has been a timeout trying to satisfy
1484  * a transmission request.
1485  *
1486  * @param cls the `struct GSF_PeerTransmitHandle` of the request
1487  */
1488 static void
1489 peer_transmit_timeout (void *cls)
1490 {
1491   struct GSF_PeerTransmitHandle *pth = cls;
1492   struct GSF_ConnectedPeer *cp;
1493
1494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1495               "Timeout trying to transmit to other peer\n");
1496   pth->timeout_task = NULL;
1497   cp = pth->cp;
1498   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1499                                cp->pth_tail,
1500                                pth);
1501   if (GNUNET_YES == pth->is_query)
1502     GNUNET_assert (0 < cp->ppd.pending_queries--);
1503   else if (GNUNET_NO == pth->is_query)
1504     GNUNET_assert (0 < cp->ppd.pending_replies--);
1505   GNUNET_LOAD_update (cp->ppd.transmission_delay,
1506                       UINT64_MAX);
1507   if (NULL != cp->cth)
1508   {
1509     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1510     cp->cth = NULL;
1511   }
1512   pth->gmc (pth->gmc_cls, 0, NULL);
1513   GNUNET_assert (0 == cp->cth_in_progress);
1514   GNUNET_free (pth);
1515 }
1516
1517
1518 /**
1519  * Transmit a message to the given peer as soon as possible.
1520  * If the peer disconnects before the transmission can happen,
1521  * the callback is invoked with a `NULL` @a buffer.
1522  *
1523  * @param cp target peer
1524  * @param is_query is this a query (#GNUNET_YES) or content (#GNUNET_NO) or neither (#GNUNET_SYSERR)
1525  * @param priority how important is this request?
1526  * @param timeout when does this request timeout (call gmc with error)
1527  * @param size number of bytes we would like to send to the peer
1528  * @param gmc function to call to get the message
1529  * @param gmc_cls closure for @a gmc
1530  * @return handle to cancel request
1531  */
1532 struct GSF_PeerTransmitHandle *
1533 GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp,
1534                     int is_query,
1535                     uint32_t priority,
1536                     struct GNUNET_TIME_Relative timeout,
1537                     size_t size,
1538                     GSF_GetMessageCallback gmc, void *gmc_cls)
1539 {
1540   struct GSF_PeerTransmitHandle *pth;
1541   struct GSF_PeerTransmitHandle *pos;
1542   struct GSF_PeerTransmitHandle *prev;
1543
1544   pth = GNUNET_new (struct GSF_PeerTransmitHandle);
1545   pth->transmission_request_start_time = GNUNET_TIME_absolute_get ();
1546   pth->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1547   pth->gmc = gmc;
1548   pth->gmc_cls = gmc_cls;
1549   pth->size = size;
1550   pth->is_query = is_query;
1551   pth->priority = priority;
1552   pth->cp = cp;
1553   /* insertion sort (by priority, descending) */
1554   prev = NULL;
1555   pos = cp->pth_head;
1556   while ((NULL != pos) && (pos->priority > priority))
1557   {
1558     prev = pos;
1559     pos = pos->next;
1560   }
1561   GNUNET_CONTAINER_DLL_insert_after (cp->pth_head,
1562                                      cp->pth_tail,
1563                                      prev,
1564                                      pth);
1565   if (GNUNET_YES == is_query)
1566     cp->ppd.pending_queries++;
1567   else if (GNUNET_NO == is_query)
1568     cp->ppd.pending_replies++;
1569   pth->timeout_task
1570     = GNUNET_SCHEDULER_add_delayed (timeout,
1571                                     &peer_transmit_timeout,
1572                                     pth);
1573   schedule_transmission (pth);
1574   return pth;
1575 }
1576
1577
1578 /**
1579  * Cancel an earlier request for transmission.
1580  *
1581  * @param pth request to cancel
1582  */
1583 void
1584 GSF_peer_transmit_cancel_ (struct GSF_PeerTransmitHandle *pth)
1585 {
1586   struct GSF_ConnectedPeer *cp;
1587
1588   if (NULL != pth->timeout_task)
1589   {
1590     GNUNET_SCHEDULER_cancel (pth->timeout_task);
1591     pth->timeout_task = NULL;
1592   }
1593   cp = pth->cp;
1594   GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1595                                cp->pth_tail,
1596                                pth);
1597   if (GNUNET_YES == pth->is_query)
1598     GNUNET_assert (0 < cp->ppd.pending_queries--);
1599   else if (GNUNET_NO == pth->is_query)
1600     GNUNET_assert (0 < cp->ppd.pending_replies--);
1601   GNUNET_free (pth);
1602 }
1603
1604
1605 /**
1606  * Report on receiving a reply; update the performance record of the given peer.
1607  *
1608  * @param cp responding peer (will be updated)
1609  * @param request_time time at which the original query was transmitted
1610  * @param request_priority priority of the original request
1611  */
1612 void
1613 GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp,
1614                               struct GNUNET_TIME_Absolute request_time,
1615                               uint32_t request_priority)
1616 {
1617   struct GNUNET_TIME_Relative delay;
1618
1619   delay = GNUNET_TIME_absolute_get_duration (request_time);
1620   cp->ppd.avg_reply_delay.rel_value_us =
1621       (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1) +
1622        delay.rel_value_us) / RUNAVG_DELAY_N;
1623   cp->ppd.avg_priority =
1624       (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1) +
1625        request_priority) / RUNAVG_DELAY_N;
1626 }
1627
1628
1629 /**
1630  * Report on receiving a reply in response to an initiating client.
1631  * Remember that this peer is good for this client.
1632  *
1633  * @param cp responding peer (will be updated)
1634  * @param initiator_client local client on responsible for query
1635  */
1636 void
1637 GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp,
1638                                    struct GSF_LocalClient *initiator_client)
1639 {
1640   cp->ppd.last_client_replies[cp->last_client_replies_woff++ %
1641                               CS2P_SUCCESS_LIST_SIZE] = initiator_client;
1642 }
1643
1644
1645 /**
1646  * Report on receiving a reply in response to an initiating peer.
1647  * Remember that this peer is good for this initiating peer.
1648  *
1649  * @param cp responding peer (will be updated)
1650  * @param initiator_peer other peer responsible for query
1651  */
1652 void
1653 GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp,
1654                                  const struct GSF_ConnectedPeer *initiator_peer)
1655 {
1656   unsigned int woff;
1657
1658   woff = cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE;
1659   GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[woff], -1);
1660   cp->ppd.last_p2p_replies[woff] = initiator_peer->ppd.pid;
1661   GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1);
1662   cp->last_p2p_replies_woff = (woff + 1) % P2P_SUCCESS_LIST_SIZE;
1663 }
1664
1665
1666 /**
1667  * Write peer-respect information to a file - flush the buffer entry!
1668  *
1669  * @param cls unused
1670  * @param key peer identity
1671  * @param value the `struct GSF_ConnectedPeer` to flush
1672  * @return #GNUNET_OK to continue iteration
1673  */
1674 static int
1675 flush_respect (void *cls,
1676                const struct GNUNET_PeerIdentity *key,
1677                void *value)
1678 {
1679   struct GSF_ConnectedPeer *cp = value;
1680   struct GNUNET_PeerIdentity pid;
1681
1682   if (cp->ppd.respect == cp->disk_respect)
1683     return GNUNET_OK;           /* unchanged */
1684   GNUNET_assert (0 != cp->ppd.pid);
1685   GNUNET_PEER_resolve (cp->ppd.pid, &pid);
1686   GNUNET_PEERSTORE_store (peerstore, "fs", &pid, "respect", &cp->ppd.respect,
1687                           sizeof (cp->ppd.respect),
1688                           GNUNET_TIME_UNIT_FOREVER_ABS,
1689                           GNUNET_PEERSTORE_STOREOPTION_REPLACE, NULL, NULL);
1690   return GNUNET_OK;
1691 }
1692
1693
1694 /**
1695  * A peer disconnected from us.  Tear down the connected peer
1696  * record.
1697  *
1698  * @param cls unused
1699  * @param peer identity of peer that connected
1700  */
1701 void
1702 GSF_peer_disconnect_handler_ (void *cls,
1703                               const struct GNUNET_PeerIdentity *peer)
1704 {
1705   struct GSF_ConnectedPeer *cp;
1706   struct GSF_PeerTransmitHandle *pth;
1707   struct GSF_DelayedHandle *dh;
1708
1709   cp = GSF_peer_get_ (peer);
1710   if (NULL == cp)
1711     return;                     /* must have been disconnect from core with
1712                                  * 'peer' == my_id, ignore */
1713   flush_respect (NULL, peer, cp);
1714   GNUNET_assert (GNUNET_YES ==
1715                  GNUNET_CONTAINER_multipeermap_remove (cp_map,
1716                                                        peer,
1717                                                        cp));
1718   GNUNET_STATISTICS_set (GSF_stats, gettext_noop ("# peers connected"),
1719                          GNUNET_CONTAINER_multipeermap_size (cp_map),
1720                          GNUNET_NO);
1721   if (NULL != cp->respect_iterate_req)
1722   {
1723     GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req);
1724     cp->respect_iterate_req = NULL;
1725   }
1726   if (NULL != cp->migration_pth)
1727   {
1728     GSF_peer_transmit_cancel_ (cp->migration_pth);
1729     cp->migration_pth = NULL;
1730   }
1731   if (NULL != cp->rc)
1732   {
1733     GNUNET_ATS_reserve_bandwidth_cancel (cp->rc);
1734     cp->rc = NULL;
1735   }
1736   if (NULL != cp->rc_delay_task)
1737   {
1738     GNUNET_SCHEDULER_cancel (cp->rc_delay_task);
1739     cp->rc_delay_task = NULL;
1740   }
1741   GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1742                                          &cancel_pending_request,
1743                                          cp);
1744   GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1745   cp->request_map = NULL;
1746   GSF_plan_notify_peer_disconnect_ (cp);
1747   GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1748   GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies,
1749                              P2P_SUCCESS_LIST_SIZE);
1750   memset (cp->ppd.last_p2p_replies,
1751           0,
1752           sizeof (cp->ppd.last_p2p_replies));
1753   GSF_push_stop_ (cp);
1754   if (NULL != cp->cth)
1755   {
1756     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1757     cp->cth = NULL;
1758   }
1759   GNUNET_assert (0 == cp->cth_in_progress);
1760   while (NULL != (pth = cp->pth_head))
1761   {
1762     if (pth->timeout_task != NULL)
1763     {
1764       GNUNET_SCHEDULER_cancel (pth->timeout_task);
1765       pth->timeout_task = NULL;
1766     }
1767     GNUNET_CONTAINER_DLL_remove (cp->pth_head,
1768                                  cp->pth_tail,
1769                                  pth);
1770     if (GNUNET_YES == pth->is_query)
1771       GNUNET_assert (0 < cp->ppd.pending_queries--);
1772     else if (GNUNET_NO == pth->is_query)
1773       GNUNET_assert (0 < cp->ppd.pending_replies--);
1774     pth->gmc (pth->gmc_cls, 0, NULL);
1775     GNUNET_free (pth);
1776   }
1777   while (NULL != (dh = cp->delayed_head))
1778   {
1779     GNUNET_CONTAINER_DLL_remove (cp->delayed_head,
1780                                  cp->delayed_tail,
1781                                  dh);
1782     cp->delay_queue_size--;
1783     GNUNET_SCHEDULER_cancel (dh->delay_task);
1784     GNUNET_free (dh->pm);
1785     GNUNET_free (dh);
1786   }
1787   GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1788   if (NULL != cp->mig_revive_task)
1789   {
1790     GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1791     cp->mig_revive_task = NULL;
1792   }
1793   GNUNET_break (0 == cp->ppd.pending_queries);
1794   GNUNET_break (0 == cp->ppd.pending_replies);
1795   GNUNET_free (cp);
1796 }
1797
1798
1799 /**
1800  * Closure for #call_iterator().
1801  */
1802 struct IterationContext
1803 {
1804   /**
1805    * Function to call on each entry.
1806    */
1807   GSF_ConnectedPeerIterator it;
1808
1809   /**
1810    * Closure for @e it.
1811    */
1812   void *it_cls;
1813 };
1814
1815
1816 /**
1817  * Function that calls the callback for each peer.
1818  *
1819  * @param cls the `struct IterationContext *`
1820  * @param key identity of the peer
1821  * @param value the `struct GSF_ConnectedPeer *`
1822  * @return #GNUNET_YES to continue iteration
1823  */
1824 static int
1825 call_iterator (void *cls,
1826                const struct GNUNET_PeerIdentity *key,
1827                void *value)
1828 {
1829   struct IterationContext *ic = cls;
1830   struct GSF_ConnectedPeer *cp = value;
1831
1832   ic->it (ic->it_cls,
1833           key, cp,
1834           &cp->ppd);
1835   return GNUNET_YES;
1836 }
1837
1838
1839 /**
1840  * Iterate over all connected peers.
1841  *
1842  * @param it function to call for each peer
1843  * @param it_cls closure for @a it
1844  */
1845 void
1846 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it,
1847                               void *it_cls)
1848 {
1849   struct IterationContext ic;
1850
1851   ic.it = it;
1852   ic.it_cls = it_cls;
1853   GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1854                                          &call_iterator,
1855                                          &ic);
1856 }
1857
1858
1859 /**
1860  * Obtain the identity of a connected peer.
1861  *
1862  * @param cp peer to get identity of
1863  * @param id identity to set (written to)
1864  */
1865 void
1866 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1867                                   struct GNUNET_PeerIdentity *id)
1868 {
1869   GNUNET_assert (0 != cp->ppd.pid);
1870   GNUNET_PEER_resolve (cp->ppd.pid, id);
1871 }
1872
1873
1874 /**
1875  * Obtain the identity of a connected peer.
1876  *
1877  * @param cp peer to get identity of
1878  * @return reference to peer identity, valid until peer disconnects (!)
1879  */
1880 const struct GNUNET_PeerIdentity *
1881 GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp)
1882 {
1883   GNUNET_assert (0 != cp->ppd.pid);
1884   return GNUNET_PEER_resolve2 (cp->ppd.pid);
1885 }
1886
1887
1888 /**
1889  * Assemble a migration stop message for transmission.
1890  *
1891  * @param cls the `struct GSF_ConnectedPeer` to use
1892  * @param size number of bytes we're allowed to write to @a buf
1893  * @param buf where to copy the message
1894  * @return number of bytes copied to @a buf
1895  */
1896 static size_t
1897 create_migration_stop_message (void *cls,
1898                                size_t size,
1899                                void *buf)
1900 {
1901   struct GSF_ConnectedPeer *cp = cls;
1902   struct MigrationStopMessage msm;
1903
1904   cp->migration_pth = NULL;
1905   if (NULL == buf)
1906     return 0;
1907   GNUNET_assert (size >= sizeof (struct MigrationStopMessage));
1908   msm.header.size = htons (sizeof (struct MigrationStopMessage));
1909   msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1910   msm.reserved = htonl (0);
1911   msm.duration =
1912       GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1913                                  (cp->last_migration_block));
1914   memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1915   GNUNET_STATISTICS_update (GSF_stats,
1916                             gettext_noop ("# migration stop messages sent"),
1917                             1, GNUNET_NO);
1918   return sizeof (struct MigrationStopMessage);
1919 }
1920
1921
1922 /**
1923  * Ask a peer to stop migrating data to us until the given point
1924  * in time.
1925  *
1926  * @param cp peer to ask
1927  * @param block_time until when to block
1928  */
1929 void
1930 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1931                            struct GNUNET_TIME_Absolute block_time)
1932 {
1933   if (cp->last_migration_block.abs_value_us > block_time.abs_value_us)
1934   {
1935     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1936                 "Migration already blocked for another %s\n",
1937                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining
1938                                                         (cp->last_migration_block), GNUNET_YES));
1939     return;                     /* already blocked */
1940   }
1941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n",
1942               GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (block_time),
1943                                                       GNUNET_YES));
1944   cp->last_migration_block = block_time;
1945   if (NULL != cp->migration_pth)
1946     GSF_peer_transmit_cancel_ (cp->migration_pth);
1947   cp->migration_pth =
1948       GSF_peer_transmit_ (cp, GNUNET_SYSERR, UINT32_MAX,
1949                           GNUNET_TIME_UNIT_FOREVER_REL,
1950                           sizeof (struct MigrationStopMessage),
1951                           &create_migration_stop_message, cp);
1952 }
1953
1954
1955 /**
1956  * Notify core about a preference we have for the given peer
1957  * (to allocate more resources towards it).  The change will
1958  * be communicated the next time we reserve bandwidth with
1959  * core (not instantly).
1960  *
1961  * @param cp peer to reserve bandwidth from
1962  * @param pref preference change
1963  */
1964 void
1965 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1966                                        uint64_t pref)
1967 {
1968   cp->inc_preference += pref;
1969 }
1970
1971
1972 /**
1973  * Call this method periodically to flush respect information to disk.
1974  *
1975  * @param cls closure, not used
1976  */
1977 static void
1978 cron_flush_respect (void *cls)
1979 {
1980   const struct GNUNET_SCHEDULER_TaskContext *tc;
1981
1982   if (NULL == cp_map)
1983     return;
1984   GNUNET_CONTAINER_multipeermap_iterate (cp_map,
1985                                          &flush_respect, NULL);
1986   tc = GNUNET_SCHEDULER_get_task_context ();
1987   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1988     return;
1989   GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ,
1990                                               GNUNET_SCHEDULER_PRIORITY_HIGH,
1991                                               &cron_flush_respect, NULL);
1992 }
1993
1994
1995 /**
1996  * Initialize peer management subsystem.
1997  */
1998 void
1999 GSF_connected_peer_init_ ()
2000 {
2001   cp_map = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2002   peerstore = GNUNET_PEERSTORE_connect (GSF_cfg);
2003   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
2004                                       &cron_flush_respect, NULL);
2005 }
2006
2007
2008 /**
2009  * Iterator to free peer entries.
2010  *
2011  * @param cls closure, unused
2012  * @param key current key code
2013  * @param value value in the hash map (peer entry)
2014  * @return #GNUNET_YES (we should continue to iterate)
2015  */
2016 static int
2017 clean_peer (void *cls,
2018             const struct GNUNET_PeerIdentity *key,
2019             void *value)
2020 {
2021   GSF_peer_disconnect_handler_ (NULL, key);
2022   return GNUNET_YES;
2023 }
2024
2025
2026 /**
2027  * Shutdown peer management subsystem.
2028  */
2029 void
2030 GSF_connected_peer_done_ ()
2031 {
2032   GNUNET_CONTAINER_multipeermap_iterate (cp_map,
2033                                          &flush_respect,
2034                                          NULL);
2035   GNUNET_CONTAINER_multipeermap_iterate (cp_map,
2036                                          &clean_peer, NULL);
2037   GNUNET_CONTAINER_multipeermap_destroy (cp_map);
2038   cp_map = NULL;
2039   GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_YES);
2040 }
2041
2042
2043 /**
2044  * Iterator to remove references to LC entry.
2045  *
2046  * @param cls the `struct GSF_LocalClient *` to look for
2047  * @param key current key code
2048  * @param value value in the hash map (peer entry)
2049  * @return #GNUNET_YES (we should continue to iterate)
2050  */
2051 static int
2052 clean_local_client (void *cls,
2053                     const struct GNUNET_PeerIdentity *key,
2054                     void *value)
2055 {
2056   const struct GSF_LocalClient *lc = cls;
2057   struct GSF_ConnectedPeer *cp = value;
2058   unsigned int i;
2059
2060   for (i = 0; i < CS2P_SUCCESS_LIST_SIZE; i++)
2061     if (cp->ppd.last_client_replies[i] == lc)
2062       cp->ppd.last_client_replies[i] = NULL;
2063   return GNUNET_YES;
2064 }
2065
2066
2067 /**
2068  * Notification that a local client disconnected.  Clean up all of our
2069  * references to the given handle.
2070  *
2071  * @param lc handle to the local client (henceforth invalid)
2072  */
2073 void
2074 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
2075 {
2076   if (NULL == cp_map)
2077     return;                     /* already cleaned up */
2078   GNUNET_CONTAINER_multipeermap_iterate (cp_map, &clean_local_client,
2079                                          (void *) lc);
2080 }
2081
2082
2083 /* end of gnunet-service-fs_cp.c */