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