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