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