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