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