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