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