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