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