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