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