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