fs crashing in integraton tests
[oweals/gnunet.git] / src / fs / gnunet-service-fs_cp.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_cp.c
23  * @brief API to handle 'connected peers'
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_load_lib.h"
28 #include "gnunet-service-fs.h"
29 #include "gnunet-service-fs_cp.h"
30 #include "gnunet-service-fs_pe.h"
31 #include "gnunet-service-fs_pr.h"
32 #include "gnunet-service-fs_push.h"
33
34
35 /**
36  * Ratio for moving average delay calculation.  The previous
37  * average goes in with a factor of (n-1) into the calculation.
38  * Must be > 0.
39  */
40 #define RUNAVG_DELAY_N 16
41
42 /**
43  * How often do we flush respect values to disk?
44  */
45 #define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
46
47 /**
48  * After how long do we discard a reply?
49  */
50 #define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
51
52 /**
53  * Collect an instane number of statistics?  May cause excessive IPC.
54  */
55 #define INSANE_STATISTICS GNUNET_NO
56
57
58 /**
59  * Handle to cancel a transmission request.
60  */
61 struct GSF_PeerTransmitHandle
62 {
63
64   /**
65    * Kept in a doubly-linked list.
66    */
67   struct GSF_PeerTransmitHandle *next;
68
69   /**
70    * Kept in a doubly-linked list.
71    */
72   struct GSF_PeerTransmitHandle *prev;
73
74   /**
75    * Time when this transmission request was issued.
76    */
77   struct GNUNET_TIME_Absolute transmission_request_start_time;
78
79   /**
80    * Timeout for this request.
81    */
82   struct GNUNET_TIME_Absolute timeout;
83
84   /**
85    * Task called on timeout, or 0 for none.
86    */
87   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
88
89   /**
90    * Function to call to get the actual message.
91    */
92   GSF_GetMessageCallback gmc;
93
94   /**
95    * Peer this request targets.
96    */
97   struct GSF_ConnectedPeer *cp;
98
99   /**
100    * Closure for 'gmc'.
101    */
102   void *gmc_cls;
103
104   /**
105    * Size of the message to be transmitted.
106    */
107   size_t size;
108
109   /**
110    * GNUNET_YES if this is a query, GNUNET_NO for content.
111    */
112   int is_query;
113
114   /**
115    * Did we get a reservation already?
116    */
117   int was_reserved;
118
119   /**
120    * Priority of this request.
121    */
122   uint32_t priority;
123
124 };
125
126
127 /**
128  * Handle for an entry in our delay list.
129  */
130 struct GSF_DelayedHandle
131 {
132
133   /**
134    * Kept in a doubly-linked list.
135    */
136   struct GSF_DelayedHandle *next;
137
138   /**
139    * Kept in a doubly-linked list.
140    */
141   struct GSF_DelayedHandle *prev;
142
143   /**
144    * Peer this transmission belongs to.
145    */
146   struct GSF_ConnectedPeer *cp;
147
148   /**
149    * The PUT that was delayed.
150    */
151   struct PutMessage *pm;
152
153   /**
154    * Task for the delay.
155    */
156   GNUNET_SCHEDULER_TaskIdentifier delay_task;
157
158   /**
159    * Size of the message.
160    */
161   size_t msize;
162
163 };
164
165
166 /**
167  * Information per peer and request.
168  */
169 struct PeerRequest
170 {
171
172   /**
173    * Handle to generic request.
174    */
175   struct GSF_PendingRequest *pr;
176
177   /**
178    * Handle to specific peer.
179    */
180   struct GSF_ConnectedPeer *cp;
181
182   /**
183    * Task for asynchronous stopping of this request.
184    */
185   GNUNET_SCHEDULER_TaskIdentifier kill_task;
186
187 };
188
189
190 /**
191  * A connected peer.
192  */
193 struct GSF_ConnectedPeer
194 {
195
196   /**
197    * Performance data for this peer.
198    */
199   struct GSF_PeerPerformanceData ppd;
200
201   /**
202    * Time until when we blocked this peer from migrating
203    * data to us.
204    */
205   struct GNUNET_TIME_Absolute last_migration_block;
206
207   /**
208    * Task scheduled to revive migration to this peer.
209    */
210   GNUNET_SCHEDULER_TaskIdentifier mig_revive_task;
211
212   /**
213    * Messages (replies, queries, content migration) we would like to
214    * send to this peer in the near future.  Sorted by priority, head.
215    */
216   struct GSF_PeerTransmitHandle *pth_head;
217
218   /**
219    * Messages (replies, queries, content migration) we would like to
220    * send to this peer in the near future.  Sorted by priority, tail.
221    */
222   struct GSF_PeerTransmitHandle *pth_tail;
223
224   /**
225    * Messages (replies, queries, content migration) we would like to
226    * send to this peer in the near future.  Sorted by priority, head.
227    */
228   struct GSF_DelayedHandle *delayed_head;
229
230   /**
231    * Messages (replies, queries, content migration) we would like to
232    * send to this peer in the near future.  Sorted by priority, tail.
233    */
234   struct GSF_DelayedHandle *delayed_tail;
235
236   /**
237    * Migration stop message in our queue, or NULL if we have none pending.
238    */
239   struct GSF_PeerTransmitHandle *migration_pth;
240
241   /**
242    * Context of our GNUNET_ATS_reserve_bandwidth call (or NULL).
243    */
244   struct GNUNET_ATS_ReservationContext *rc;
245
246   /**
247    * Task scheduled if we need to retry bandwidth reservation later.
248    */
249   GNUNET_SCHEDULER_TaskIdentifier rc_delay_task;
250
251   /**
252    * Active requests from this neighbour, map of query to 'struct PeerRequest'.
253    */
254   struct GNUNET_CONTAINER_MultiHashMap *request_map;
255
256   /**
257    * Handle for an active request for transmission to this
258    * peer, or NULL (if core queue was full).
259    */
260   struct GNUNET_CORE_TransmitHandle *cth;
261
262   /**
263    * Increase in traffic preference still to be submitted
264    * to the core service for this peer.
265    */
266   uint64_t inc_preference;
267
268   /**
269    * Set to 1 if we're currently in the process of calling
270    * 'GNUNET_CORE_notify_transmit_ready' (so while cth is
271    * NULL, we should not call notify_transmit_ready for this
272    * handle right now).
273    */
274   unsigned int cth_in_progress;
275
276   /**
277    * Respect rating for this peer on disk.
278    */
279   uint32_t disk_respect;
280
281   /**
282    * Which offset in "last_p2p_replies" will be updated next?
283    * (we go round-robin).
284    */
285   unsigned int last_p2p_replies_woff;
286
287   /**
288    * Which offset in "last_client_replies" will be updated next?
289    * (we go round-robin).
290    */
291   unsigned int last_client_replies_woff;
292
293   /**
294    * Current offset into 'last_request_times' ring buffer.
295    */
296   unsigned int last_request_times_off;
297
298   /**
299    * GNUNET_YES if we did successfully reserve 32k bandwidth,
300    * GNUNET_NO if not.
301    */
302   int did_reserve;
303
304 };
305
306
307 /**
308  * Map from peer identities to 'struct GSF_ConnectPeer' entries.
309  */
310 static struct GNUNET_CONTAINER_MultiHashMap *cp_map;
311
312 /**
313  * Where do we store respect information?
314  */
315 static char *respectDirectory;
316
317
318 /**
319  * Get the filename under which we would store respect
320  * for the given peer.
321  *
322  * @param id peer to get the filename for
323  * @return filename of the form DIRECTORY/PEERID
324  */
325 static char *
326 get_respect_filename (const struct GNUNET_PeerIdentity *id)
327 {
328   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
329   char *fn;
330
331   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
332   GNUNET_asprintf (&fn, "%s%s%s", respectDirectory, DIR_SEPARATOR_STR, &fil);
333   return fn;
334 }
335
336
337 /**
338  * Update the latency information kept for the given peer.
339  *
340  * @param id peer record to update
341  * @param latency current latency value
342  */
343 void
344 GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id,
345                           struct GNUNET_TIME_Relative latency)
346 {
347   struct GSF_ConnectedPeer *cp;
348
349   cp = GSF_peer_get_ (id);
350
351   if (NULL == cp)
352   {
353                 GNUNET_break (0);
354                 return;
355   }
356
357   GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay, latency);
358   /* LATER: merge atsi into cp's performance data (if we ever care...) */
359 }
360
361
362 /**
363  * Return the performance data record for the given peer
364  *
365  * @param cp peer to query
366  * @return performance data record for the peer
367  */
368 struct GSF_PeerPerformanceData *
369 GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp)
370 {
371   return &cp->ppd;
372 }
373
374
375 /**
376  * Core is ready to transmit to a peer, get the message.
377  *
378  * @param cls the 'struct GSF_PeerTransmitHandle' of the message
379  * @param size number of bytes core is willing to take
380  * @param buf where to copy the message
381  * @return number of bytes copied to buf
382  */
383 static size_t
384 peer_transmit_ready_cb (void *cls, size_t size, void *buf);
385
386
387 /**
388  * Function called by core upon success or failure of our bandwidth reservation request.
389  *
390  * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
391  * @param peer identifies the peer
392  * @param amount set to the amount that was actually reserved or unreserved;
393  *               either the full requested amount or zero (no partial reservations)
394  * @param res_delay if the reservation could not be satisfied (amount was 0), how
395  *        long should the client wait until re-trying?
396  */
397 static void
398 ats_reserve_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
399                       int32_t amount, struct GNUNET_TIME_Relative res_delay);
400
401
402 /**
403  * If ready (bandwidth reserved), try to schedule transmission via
404  * core for the given handle.
405  *
406  * @param pth transmission handle to schedule
407  */
408 static void
409 schedule_transmission (struct GSF_PeerTransmitHandle *pth)
410 {
411   struct GSF_ConnectedPeer *cp;
412   struct GNUNET_PeerIdentity target;
413
414   cp = pth->cp;
415   if ((NULL != cp->cth) || (0 != cp->cth_in_progress))
416     return;                     /* already done */
417   GNUNET_assert (0 != cp->ppd.pid);
418   GNUNET_PEER_resolve (cp->ppd.pid, &target);
419
420   if (0 != cp->inc_preference)
421   {
422     GNUNET_ATS_change_preference (GSF_ats, &target, GNUNET_ATS_PREFERENCE_BANDWIDTH,
423                                   (double) cp->inc_preference,
424                                   GNUNET_ATS_PREFERENCE_END);
425     cp->inc_preference = 0;
426   }
427
428   if ((GNUNET_YES == pth->is_query) && (GNUNET_YES != pth->was_reserved))
429   {
430     /* query, need reservation */
431     if (GNUNET_YES != cp->did_reserve)
432       return;                   /* not ready */
433     cp->did_reserve = GNUNET_NO;
434     /* reservation already done! */
435     pth->was_reserved = GNUNET_YES;
436     cp->rc =
437         GNUNET_ATS_reserve_bandwidth (GSF_ats, &target, DBLOCK_SIZE,
438                                       &ats_reserve_callback, cp);
439     return;
440   }
441   GNUNET_assert (NULL == cp->cth);
442   cp->cth_in_progress++;
443   cp->cth =
444     GNUNET_CORE_notify_transmit_ready (GSF_core, GNUNET_YES, pth->priority,
445                                        GNUNET_TIME_absolute_get_remaining
446                                        (pth->timeout), &target, pth->size,
447                                        &peer_transmit_ready_cb, cp);
448   GNUNET_assert (NULL != cp->cth);
449   GNUNET_assert (0 < cp->cth_in_progress--);
450 }
451
452
453 /**
454  * Core is ready to transmit to a peer, get the message.
455  *
456  * @param cls the 'struct GSF_PeerTransmitHandle' of the message
457  * @param size number of bytes core is willing to take
458  * @param buf where to copy the message
459  * @return number of bytes copied to buf
460  */
461 static size_t
462 peer_transmit_ready_cb (void *cls, size_t size, void *buf)
463 {
464   struct GSF_ConnectedPeer *cp = cls;
465   struct GSF_PeerTransmitHandle *pth = cp->pth_head;
466   struct GSF_PeerTransmitHandle *pos;
467   size_t ret;
468
469   cp->cth = NULL;
470   if (NULL == pth)
471     return 0;
472   if (pth->size > size)
473   {
474     schedule_transmission (pth);
475     return 0;
476   }
477   if (GNUNET_SCHEDULER_NO_TASK != pth->timeout_task)
478   {
479     GNUNET_SCHEDULER_cancel (pth->timeout_task);
480     pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
481   }
482   GNUNET_CONTAINER_DLL_remove (cp->pth_head, cp->pth_tail, pth);
483   if (GNUNET_YES == pth->is_query)
484   {
485     cp->ppd.last_request_times[(cp->last_request_times_off++) %
486                                MAX_QUEUE_PER_PEER] =
487         GNUNET_TIME_absolute_get ();
488     GNUNET_assert (0 < cp->ppd.pending_queries--);
489   }
490   else if (GNUNET_NO == pth->is_query)
491   {
492     GNUNET_assert (0 < cp->ppd.pending_replies--);
493   }
494   GNUNET_LOAD_update (cp->ppd.transmission_delay,
495                       GNUNET_TIME_absolute_get_duration
496                       (pth->transmission_request_start_time).rel_value);
497   ret = pth->gmc (pth->gmc_cls, size, buf);
498   if (NULL != (pos = cp->pth_head))
499   {
500     GNUNET_assert (pos != pth);
501     schedule_transmission (pos);
502   }
503   GNUNET_free (pth);
504   return ret;
505 }
506
507
508 /**
509  * (re)try to reserve bandwidth from the given peer.
510  *
511  * @param cls the 'struct GSF_ConnectedPeer' to reserve from
512  * @param tc scheduler context
513  */
514 static void
515 retry_reservation (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
516 {
517   struct GSF_ConnectedPeer *cp = cls;
518   struct GNUNET_PeerIdentity target;
519
520   GNUNET_PEER_resolve (cp->ppd.pid, &target);
521   cp->rc_delay_task = GNUNET_SCHEDULER_NO_TASK;
522   cp->rc =
523     GNUNET_ATS_reserve_bandwidth (GSF_ats, &target, DBLOCK_SIZE,
524                                   &ats_reserve_callback, cp);
525 }
526
527
528 /**
529  * Function called by core upon success or failure of our bandwidth reservation request.
530  *
531  * @param cls the 'struct GSF_ConnectedPeer' of the peer for which we made the request
532  * @param peer identifies the peer
533  * @param amount set to the amount that was actually reserved or unreserved;
534  *               either the full requested amount or zero (no partial reservations)
535  * @param res_delay if the reservation could not be satisfied (amount was 0), how
536  *        long should the client wait until re-trying?
537  */
538 static void
539 ats_reserve_callback (void *cls, const struct GNUNET_PeerIdentity *peer,
540                       int32_t amount, struct GNUNET_TIME_Relative res_delay)
541 {
542   struct GSF_ConnectedPeer *cp = cls;
543   struct GSF_PeerTransmitHandle *pth;
544
545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
546               "Reserved %d bytes / need to wait %s for reservation\n",
547               (int) amount, 
548               GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES));
549   cp->rc = NULL;
550   if (0 == amount)
551   {
552     cp->rc_delay_task =
553         GNUNET_SCHEDULER_add_delayed (res_delay, &retry_reservation, cp);
554     return;
555   }
556   cp->did_reserve = GNUNET_YES;
557   pth = cp->pth_head;
558   if ((NULL != pth) && (NULL == cp->cth) && (0 == cp->cth_in_progress))
559   {
560     /* reservation success, try transmission now! */
561     cp->cth_in_progress++;
562     cp->cth =
563         GNUNET_CORE_notify_transmit_ready (GSF_core, GNUNET_YES, pth->priority,
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_malloc (sizeof (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_multihashmap_put (cp_map, 
603                                                    &GSF_connected_peer_get_identity2_ (cp)->hashPubKey,
604                                                    cp,
605                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
606   GNUNET_STATISTICS_set (GSF_stats, gettext_noop ("# peers connected"),
607                          GNUNET_CONTAINER_multihashmap_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)
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_multihashmap_get (cp_map, &peer->hashPubKey);
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 + 1));
842 #if INSANE_STATISTICS
843   GNUNET_STATISTICS_update (GSF_stats,
844                             gettext_noop
845                             ("# artificial delays introduced (ms)"),
846                             ret.rel_value, 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_malloc (sizeof (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_HashCode *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_HashCode))
1152   {
1153     GNUNET_break_op (0);
1154     return NULL;
1155   }
1156   opt = (const struct GNUNET_HashCode *) &gm[1];
1157   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (struct GNUNET_HashCode);
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_ ((const struct GNUNET_PeerIdentity *) &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 ((const struct GNUNET_PeerIdentity *)
1187                               &opt[bits - 1]));
1188
1189     else
1190       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1191                   "Failed to find peer `%4s' in connection set. Dropping query.\n",
1192                   GNUNET_i2s (other));
1193 #if INSANE_STATISTICS
1194     GNUNET_STATISTICS_update (GSF_stats,
1195                               gettext_noop
1196                               ("# requests dropped due to missing reverse route"),
1197                               1, GNUNET_NO);
1198 #endif
1199     return NULL;
1200   }
1201   /* note that we can really only check load here since otherwise
1202    * peers could find out that we are overloaded by not being
1203    * disconnected after sending us a malformed query... */
1204   priority = bound_priority (ntohl (gm->priority), cps);
1205   if (priority < 0)
1206   {
1207     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1208                 "Dropping query from `%s', this peer is too busy.\n",
1209                 GNUNET_i2s (other));
1210     return NULL;
1211   }
1212   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1213               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
1214               GNUNET_h2s (&gm->query), (unsigned int) type, GNUNET_i2s (other),
1215               (unsigned int) bm);
1216   target =
1217       (0 !=
1218        (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? ((const struct GNUNET_PeerIdentity
1219                                                *) &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 * 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 >= GNUNET_TIME_absolute_get ().abs_value + ttl)
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_malloc (sizeof (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' 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 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_malloc (sizeof (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 =
1434       (cp->ppd.avg_reply_delay.rel_value * (RUNAVG_DELAY_N - 1) +
1435        delay.rel_value) / 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_multihashmap_remove (cp_map,
1499                                                        &peer->hashPubKey, cp));
1500   GNUNET_STATISTICS_set (GSF_stats, gettext_noop ("# peers connected"),
1501                          GNUNET_CONTAINER_multihashmap_size (cp_map),
1502                          GNUNET_NO);
1503   if (NULL != cp->migration_pth)
1504   {
1505     GSF_peer_transmit_cancel_ (cp->migration_pth);
1506     cp->migration_pth = NULL;
1507   }
1508   if (NULL != cp->rc)
1509   {
1510     GNUNET_ATS_reserve_bandwidth_cancel (cp->rc);
1511     cp->rc = NULL;
1512   }
1513   if (GNUNET_SCHEDULER_NO_TASK != cp->rc_delay_task)
1514   {
1515     GNUNET_SCHEDULER_cancel (cp->rc_delay_task);
1516     cp->rc_delay_task = GNUNET_SCHEDULER_NO_TASK;
1517   }
1518   GNUNET_CONTAINER_multihashmap_iterate (cp->request_map,
1519                                          &cancel_pending_request, cp);
1520   GNUNET_CONTAINER_multihashmap_destroy (cp->request_map);
1521   cp->request_map = NULL;
1522   GSF_plan_notify_peer_disconnect_ (cp);
1523   GNUNET_LOAD_value_free (cp->ppd.transmission_delay);
1524   GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1525   memset (cp->ppd.last_p2p_replies, 0, sizeof (cp->ppd.last_p2p_replies));
1526   GSF_push_stop_ (cp);
1527   if (NULL != cp->cth)
1528   {
1529     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1530     cp->cth = NULL;
1531   }
1532   GNUNET_assert (0 == cp->cth_in_progress);
1533   while (NULL != (pth = cp->pth_head))
1534   {
1535     if (pth->timeout_task != GNUNET_SCHEDULER_NO_TASK)
1536     {
1537       GNUNET_SCHEDULER_cancel (pth->timeout_task);
1538       pth->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1539     }
1540     GNUNET_CONTAINER_DLL_remove (cp->pth_head, cp->pth_tail, pth);
1541     pth->gmc (pth->gmc_cls, 0, NULL);
1542     GNUNET_free (pth);
1543   }
1544   while (NULL != (dh = cp->delayed_head))
1545   {
1546     GNUNET_CONTAINER_DLL_remove (cp->delayed_head, cp->delayed_tail, dh);
1547     GNUNET_SCHEDULER_cancel (dh->delay_task);
1548     GNUNET_free (dh->pm);
1549     GNUNET_free (dh);
1550   }
1551   GNUNET_PEER_change_rc (cp->ppd.pid, -1);
1552   if (GNUNET_SCHEDULER_NO_TASK != cp->mig_revive_task)
1553   {
1554     GNUNET_SCHEDULER_cancel (cp->mig_revive_task);
1555     cp->mig_revive_task = GNUNET_SCHEDULER_NO_TASK;
1556   }
1557   GNUNET_free (cp);
1558 }
1559
1560
1561 /**
1562  * Closure for 'call_iterator'.
1563  */
1564 struct IterationContext
1565 {
1566   /**
1567    * Function to call on each entry.
1568    */
1569   GSF_ConnectedPeerIterator it;
1570
1571   /**
1572    * Closure for 'it'.
1573    */
1574   void *it_cls;
1575 };
1576
1577
1578 /**
1579  * Function that calls the callback for each peer.
1580  *
1581  * @param cls the 'struct IterationContext*'
1582  * @param key identity of the peer
1583  * @param value the 'struct GSF_ConnectedPeer*'
1584  * @return GNUNET_YES to continue iteration
1585  */
1586 static int
1587 call_iterator (void *cls, const struct GNUNET_HashCode * key, void *value)
1588 {
1589   struct IterationContext *ic = cls;
1590   struct GSF_ConnectedPeer *cp = value;
1591
1592   ic->it (ic->it_cls, (const struct GNUNET_PeerIdentity *) key, cp, &cp->ppd);
1593   return GNUNET_YES;
1594 }
1595
1596
1597 /**
1598  * Iterate over all connected peers.
1599  *
1600  * @param it function to call for each peer
1601  * @param it_cls closure for it
1602  */
1603 void
1604 GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it, void *it_cls)
1605 {
1606   struct IterationContext ic;
1607
1608   ic.it = it;
1609   ic.it_cls = it_cls;
1610   GNUNET_CONTAINER_multihashmap_iterate (cp_map, &call_iterator, &ic);
1611 }
1612
1613
1614 /**
1615  * Obtain the identity of a connected peer.
1616  *
1617  * @param cp peer to get identity of
1618  * @param id identity to set (written to)
1619  */
1620 void
1621 GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp,
1622                                   struct GNUNET_PeerIdentity *id)
1623 {
1624   GNUNET_assert (0 != cp->ppd.pid);
1625   GNUNET_PEER_resolve (cp->ppd.pid, id);
1626 }
1627
1628
1629 /**
1630  * Obtain the identity of a connected peer.
1631  *
1632  * @param cp peer to get identity of
1633  * @return reference to peer identity, valid until peer disconnects (!)
1634  */
1635 const struct GNUNET_PeerIdentity *
1636 GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp)
1637 {
1638   GNUNET_assert (0 != cp->ppd.pid);
1639   return GNUNET_PEER_resolve2 (cp->ppd.pid);
1640 }
1641
1642
1643 /**
1644  * Assemble a migration stop message for transmission.
1645  *
1646  * @param cls the 'struct GSF_ConnectedPeer' to use
1647  * @param size number of bytes we're allowed to write to buf
1648  * @param buf where to copy the message
1649  * @return number of bytes copied to buf
1650  */
1651 static size_t
1652 create_migration_stop_message (void *cls, size_t size, void *buf)
1653 {
1654   struct GSF_ConnectedPeer *cp = cls;
1655   struct MigrationStopMessage msm;
1656
1657   cp->migration_pth = NULL;
1658   if (NULL == buf)
1659     return 0;
1660   GNUNET_assert (size >= sizeof (struct MigrationStopMessage));
1661   msm.header.size = htons (sizeof (struct MigrationStopMessage));
1662   msm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
1663   msm.reserved = htonl (0);
1664   msm.duration =
1665       GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1666                                  (cp->last_migration_block));
1667   memcpy (buf, &msm, sizeof (struct MigrationStopMessage));
1668   GNUNET_STATISTICS_update (GSF_stats,
1669                             gettext_noop ("# migration stop messages sent"),
1670                             1, GNUNET_NO);
1671   return sizeof (struct MigrationStopMessage);
1672 }
1673
1674
1675 /**
1676  * Ask a peer to stop migrating data to us until the given point
1677  * in time.
1678  *
1679  * @param cp peer to ask
1680  * @param block_time until when to block
1681  */
1682 void
1683 GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp,
1684                            struct GNUNET_TIME_Absolute block_time)
1685 {
1686   if (cp->last_migration_block.abs_value > block_time.abs_value)
1687   {
1688     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689                 "Migration already blocked for another %s\n",
1690                 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining
1691                                                         (cp->last_migration_block), GNUNET_YES));
1692     return;                     /* already blocked */
1693   }
1694   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %llu ms\n",
1695               (unsigned long long) GNUNET_TIME_absolute_get_remaining (block_time).rel_value);
1696   cp->last_migration_block = block_time;
1697   if (NULL != cp->migration_pth)
1698     GSF_peer_transmit_cancel_ (cp->migration_pth);
1699   cp->migration_pth =
1700       GSF_peer_transmit_ (cp, GNUNET_SYSERR, UINT32_MAX,
1701                           GNUNET_TIME_UNIT_FOREVER_REL,
1702                           sizeof (struct MigrationStopMessage),
1703                           &create_migration_stop_message, cp);
1704 }
1705
1706
1707 /**
1708  * Write peer-respect information to a file - flush the buffer entry!
1709  *
1710  * @param cls unused
1711  * @param key peer identity
1712  * @param value the 'struct GSF_ConnectedPeer' to flush
1713  * @return GNUNET_OK to continue iteration
1714  */
1715 static int
1716 flush_respect (void *cls, const struct GNUNET_HashCode * key, void *value)
1717 {
1718   struct GSF_ConnectedPeer *cp = value;
1719   char *fn;
1720   uint32_t respect;
1721   struct GNUNET_PeerIdentity pid;
1722
1723   if (cp->ppd.respect == cp->disk_respect)
1724     return GNUNET_OK;           /* unchanged */
1725   GNUNET_assert (0 != cp->ppd.pid);
1726   GNUNET_PEER_resolve (cp->ppd.pid, &pid);
1727   fn = get_respect_filename (&pid);
1728   if (cp->ppd.respect == 0)
1729   {
1730     if ((0 != UNLINK (fn)) && (errno != ENOENT))
1731       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1732                                 GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1733   }
1734   else
1735   {
1736     respect = htonl (cp->ppd.respect);
1737     if (sizeof (uint32_t) ==
1738         GNUNET_DISK_fn_write (fn, &respect, sizeof (uint32_t),
1739                               GNUNET_DISK_PERM_USER_READ |
1740                               GNUNET_DISK_PERM_USER_WRITE |
1741                               GNUNET_DISK_PERM_GROUP_READ |
1742                               GNUNET_DISK_PERM_OTHER_READ))
1743       cp->disk_respect = cp->ppd.respect;
1744   }
1745   GNUNET_free (fn);
1746   return GNUNET_OK;
1747 }
1748
1749
1750 /**
1751  * Notify core about a preference we have for the given peer
1752  * (to allocate more resources towards it).  The change will
1753  * be communicated the next time we reserve bandwidth with
1754  * core (not instantly).
1755  *
1756  * @param cp peer to reserve bandwidth from
1757  * @param pref preference change
1758  */
1759 void
1760 GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp,
1761                                        uint64_t pref)
1762 {
1763   cp->inc_preference += pref;
1764 }
1765
1766
1767 /**
1768  * Call this method periodically to flush respect information to disk.
1769  *
1770  * @param cls closure, not used
1771  * @param tc task context, not used
1772  */
1773 static void
1774 cron_flush_respect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1775 {
1776
1777   if (NULL == cp_map)
1778     return;
1779   GNUNET_CONTAINER_multihashmap_iterate (cp_map, &flush_respect, NULL);
1780   if (NULL == tc)
1781     return;
1782   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1783     return;
1784   GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ,
1785                                               GNUNET_SCHEDULER_PRIORITY_HIGH,
1786                                               &cron_flush_respect, NULL);
1787 }
1788
1789
1790 /**
1791  * Initialize peer management subsystem.
1792  */
1793 void
1794 GSF_connected_peer_init_ ()
1795 {
1796   cp_map = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_YES);
1797   GNUNET_assert (GNUNET_OK ==
1798                  GNUNET_CONFIGURATION_get_value_filename (GSF_cfg, "fs",
1799                                                           "RESPECT",
1800                                                           &respectDirectory));
1801   GNUNET_DISK_directory_create (respectDirectory);
1802   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
1803                                       &cron_flush_respect, NULL);
1804 }
1805
1806
1807 /**
1808  * Iterator to free peer entries.
1809  *
1810  * @param cls closure, unused
1811  * @param key current key code
1812  * @param value value in the hash map (peer entry)
1813  * @return GNUNET_YES (we should continue to iterate)
1814  */
1815 static int
1816 clean_peer (void *cls, const struct GNUNET_HashCode * key, void *value)
1817 {
1818   GSF_peer_disconnect_handler_ (NULL, (const struct GNUNET_PeerIdentity *) key);
1819   return GNUNET_YES;
1820 }
1821
1822
1823 /**
1824  * Shutdown peer management subsystem.
1825  */
1826 void
1827 GSF_connected_peer_done_ ()
1828 {
1829   cron_flush_respect (NULL, NULL);
1830   GNUNET_CONTAINER_multihashmap_iterate (cp_map, &clean_peer, NULL);
1831   GNUNET_CONTAINER_multihashmap_destroy (cp_map);
1832   cp_map = NULL;
1833   GNUNET_free (respectDirectory);
1834   respectDirectory = NULL;
1835 }
1836
1837
1838 /**
1839  * Iterator to remove references to LC entry.
1840  *
1841  * @param cls the 'struct GSF_LocalClient*' to look for
1842  * @param key current key code
1843  * @param value value in the hash map (peer entry)
1844  * @return GNUNET_YES (we should continue to iterate)
1845  */
1846 static int
1847 clean_local_client (void *cls, const struct GNUNET_HashCode * key, void *value)
1848 {
1849   const struct GSF_LocalClient *lc = cls;
1850   struct GSF_ConnectedPeer *cp = value;
1851   unsigned int i;
1852
1853   for (i = 0; i < CS2P_SUCCESS_LIST_SIZE; i++)
1854     if (cp->ppd.last_client_replies[i] == lc)
1855       cp->ppd.last_client_replies[i] = NULL;
1856   return GNUNET_YES;
1857 }
1858
1859
1860 /**
1861  * Notification that a local client disconnected.  Clean up all of our
1862  * references to the given handle.
1863  *
1864  * @param lc handle to the local client (henceforth invalid)
1865  */
1866 void
1867 GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc)
1868 {
1869   if (NULL == cp_map)
1870     return;                     /* already cleaned up */
1871   GNUNET_CONTAINER_multihashmap_iterate (cp_map, &clean_local_client,
1872                                          (void *) lc);
1873 }
1874
1875
1876 /* end of gnunet-service-fs_cp.c */