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