Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / fs / gnunet-service-fs_cadet_client.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs_cadet_client.c
23  * @brief non-anonymous file-transfer
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - PORT is set to old application type, unsure if we should keep
28  *   it that way (fine for now)
29  */
30 #include "platform.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_cadet_service.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_applications.h"
36 #include "gnunet-service-fs.h"
37 #include "gnunet-service-fs_indexing.h"
38 #include "gnunet-service-fs_cadet.h"
39
40
41 /**
42  * After how long do we reset connections without replies?
43  */
44 #define CLIENT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
45
46
47 /**
48  * Handle for a cadet to another peer.
49  */
50 struct CadetHandle;
51
52
53 /**
54  * Handle for a request that is going out via cadet API.
55  */
56 struct GSF_CadetRequest
57 {
58
59   /**
60    * DLL.
61    */
62   struct GSF_CadetRequest *next;
63
64   /**
65    * DLL.
66    */
67   struct GSF_CadetRequest *prev;
68
69   /**
70    * Which cadet is this request associated with?
71    */
72   struct CadetHandle *mh;
73
74   /**
75    * Function to call with the result.
76    */
77   GSF_CadetReplyProcessor proc;
78
79   /**
80    * Closure for @e proc
81    */
82   void *proc_cls;
83
84   /**
85    * Query to transmit to the other peer.
86    */
87   struct GNUNET_HashCode query;
88
89   /**
90    * Desired type for the reply.
91    */
92   enum GNUNET_BLOCK_Type type;
93
94   /**
95    * Did we transmit this request already? #GNUNET_YES if we are
96    * in the 'waiting_map', #GNUNET_NO if we are in the 'pending' DLL.
97    */
98   int was_transmitted;
99 };
100
101
102 /**
103  * Handle for a cadet to another peer.
104  */
105 struct CadetHandle
106 {
107   /**
108    * Head of DLL of pending requests on this cadet.
109    */
110   struct GSF_CadetRequest *pending_head;
111
112   /**
113    * Tail of DLL of pending requests on this cadet.
114    */
115   struct GSF_CadetRequest *pending_tail;
116
117   /**
118    * Map from query to `struct GSF_CadetRequest`s waiting for
119    * a reply.
120    */
121   struct GNUNET_CONTAINER_MultiHashMap *waiting_map;
122
123   /**
124    * Channel to the other peer.
125    */
126   struct GNUNET_CADET_Channel *channel;
127
128   /**
129    * Which peer does this cadet go to?
130    */
131   struct GNUNET_PeerIdentity target;
132
133   /**
134    * Task to kill inactive cadets (we keep them around for
135    * a few seconds to give the application a chance to give
136    * us another query).
137    */
138   struct GNUNET_SCHEDULER_Task *timeout_task;
139
140   /**
141    * Task to reset cadets that had errors (asynchronously,
142    * as we may not be able to do it immediately during a
143    * callback from the cadet API).
144    */
145   struct GNUNET_SCHEDULER_Task *reset_task;
146
147 };
148
149
150 /**
151  * Cadet channel for creating outbound channels.
152  */
153 struct GNUNET_CADET_Handle *cadet_handle;
154
155 /**
156  * Map from peer identities to 'struct CadetHandles' with cadet
157  * channels to those peers.
158  */
159 struct GNUNET_CONTAINER_MultiPeerMap *cadet_map;
160
161
162 /* ********************* client-side code ************************* */
163
164
165 /**
166  * Transmit pending requests via the cadet.
167  *
168  * @param cls `struct CadetHandle` to process
169  */
170 static void
171 transmit_pending (void *cls);
172
173
174 /**
175  * Iterator called on each entry in a waiting map to
176  * move it back to the pending list.
177  *
178  * @param cls the `struct CadetHandle`
179  * @param key the key of the entry in the map (the query)
180  * @param value the `struct GSF_CadetRequest` to move to pending
181  * @return #GNUNET_YES (continue to iterate)
182  */
183 static int
184 move_to_pending (void *cls,
185                  const struct GNUNET_HashCode *key,
186                  void *value)
187 {
188   struct CadetHandle *mh = cls;
189   struct GSF_CadetRequest *sr = value;
190
191   GNUNET_assert (GNUNET_YES ==
192                  GNUNET_CONTAINER_multihashmap_remove (mh->waiting_map,
193                                                        key,
194                                                        value));
195   GNUNET_CONTAINER_DLL_insert (mh->pending_head,
196                                mh->pending_tail,
197                                sr);
198   sr->was_transmitted = GNUNET_NO;
199   return GNUNET_YES;
200 }
201
202
203 /**
204  * Functions with this signature are called whenever a complete reply
205  * is received.
206  *
207  * @param cls closure with the `struct CadetHandle`
208  * @param srm the actual message
209  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
210  */
211 static int
212 check_reply (void *cls,
213              const struct CadetReplyMessage *srm)
214 {
215   /* We check later... */
216   return GNUNET_OK;
217 }
218
219
220 /**
221  * Task called when it is time to reset an cadet.
222  *
223  * @param cls the `struct CadetHandle` to tear down
224  */
225 static void
226 reset_cadet_task (void *cls);
227
228
229 /**
230  * We had a serious error, tear down and re-create cadet from scratch,
231  * but do so asynchronously.
232  *
233  * @param mh cadet to reset
234  */
235 static void
236 reset_cadet_async (struct CadetHandle *mh)
237 {
238   if (NULL != mh->reset_task)
239     GNUNET_SCHEDULER_cancel (mh->reset_task);
240   mh->reset_task = GNUNET_SCHEDULER_add_now (&reset_cadet_task,
241                                              mh);
242 }
243
244
245 /**
246  * Closure for handle_reply().
247  */
248 struct HandleReplyClosure
249 {
250
251   /**
252    * Reply payload.
253    */
254   const void *data;
255
256   /**
257    * Expiration time for the block.
258    */
259   struct GNUNET_TIME_Absolute expiration;
260
261   /**
262    * Number of bytes in @e data.
263    */
264   size_t data_size;
265
266   /**
267    * Type of the block.
268    */
269   enum GNUNET_BLOCK_Type type;
270
271   /**
272    * Did we have a matching query?
273    */
274   int found;
275 };
276
277
278 /**
279  * Iterator called on each entry in a waiting map to
280  * process a result.
281  *
282  * @param cls the `struct HandleReplyClosure`
283  * @param key the key of the entry in the map (the query)
284  * @param value the `struct GSF_CadetRequest` to handle result for
285  * @return #GNUNET_YES (continue to iterate)
286  */
287 static int
288 process_reply (void *cls,
289                const struct GNUNET_HashCode *key,
290                void *value)
291 {
292   struct HandleReplyClosure *hrc = cls;
293   struct GSF_CadetRequest *sr = value;
294
295   sr->proc (sr->proc_cls,
296             hrc->type,
297             hrc->expiration,
298             hrc->data_size,
299             hrc->data);
300   sr->proc = NULL;
301   GSF_cadet_query_cancel (sr);
302   hrc->found = GNUNET_YES;
303   return GNUNET_YES;
304 }
305
306
307 /**
308  * Iterator called on each entry in a waiting map to
309  * call the 'proc' continuation and release associated
310  * resources.
311  *
312  * @param cls the `struct CadetHandle`
313  * @param key the key of the entry in the map (the query)
314  * @param value the `struct GSF_CadetRequest` to clean up
315  * @return #GNUNET_YES (continue to iterate)
316  */
317 static int
318 free_waiting_entry (void *cls,
319                     const struct GNUNET_HashCode *key,
320                     void *value)
321 {
322   struct GSF_CadetRequest *sr = value;
323
324   GSF_cadet_query_cancel (sr);
325   return GNUNET_YES;
326 }
327
328
329 /**
330  * Functions with this signature are called whenever a complete reply
331  * is received.
332  *
333  * @param cls closure with the `struct CadetHandle`
334  * @param srm the actual message
335  */
336 static void
337 handle_reply (void *cls,
338               const struct CadetReplyMessage *srm)
339 {
340   struct CadetHandle *mh = cls;
341   struct HandleReplyClosure hrc;
342   uint16_t msize;
343   enum GNUNET_BLOCK_Type type;
344   struct GNUNET_HashCode query;
345
346   msize = ntohs (srm->header.size) - sizeof (struct CadetReplyMessage);
347   type = (enum GNUNET_BLOCK_Type) ntohl (srm->type);
348   if (GNUNET_YES !=
349       GNUNET_BLOCK_get_key (GSF_block_ctx,
350                             type,
351                             &srm[1],
352                             msize,
353                             &query))
354   {
355     GNUNET_break_op (0);
356     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
357                 "Received bogus reply of type %u with %u bytes via cadet from peer %s\n",
358                 type,
359                 msize,
360                 GNUNET_i2s (&mh->target));
361     reset_cadet_async (mh);
362     return;
363   }
364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365               "Received reply `%s' via cadet from peer %s\n",
366               GNUNET_h2s (&query),
367               GNUNET_i2s (&mh->target));
368   GNUNET_CADET_receive_done (mh->channel);
369   GNUNET_STATISTICS_update (GSF_stats,
370                             gettext_noop ("# replies received via cadet"), 1,
371                             GNUNET_NO);
372   hrc.data = &srm[1];
373   hrc.data_size = msize;
374   hrc.expiration = GNUNET_TIME_absolute_ntoh (srm->expiration);
375   hrc.type = type;
376   hrc.found = GNUNET_NO;
377   GNUNET_CONTAINER_multihashmap_get_multiple (mh->waiting_map,
378                                               &query,
379                                               &process_reply,
380                                               &hrc);
381   if (GNUNET_NO == hrc.found)
382   {
383     GNUNET_STATISTICS_update (GSF_stats,
384                               gettext_noop ("# replies received via cadet dropped"), 1,
385                               GNUNET_NO);
386   }
387 }
388
389
390 /**
391  * Function called by cadet when a client disconnects.
392  * Cleans up our `struct CadetClient` of that channel.
393  *
394  * @param cls our `struct CadetClient`
395  * @param channel channel of the disconnecting client
396  */
397 static void
398 disconnect_cb (void *cls,
399                const struct GNUNET_CADET_Channel *channel)
400 {
401   struct CadetHandle *mh = cls;
402   struct GSF_CadetRequest *sr;
403
404   if (NULL == mh->channel)
405     return; /* being destroyed elsewhere */
406   GNUNET_assert (channel == mh->channel);
407   mh->channel = NULL;
408   while (NULL != (sr = mh->pending_head))
409     GSF_cadet_query_cancel (sr);
410   /* first remove `mh` from the `cadet_map`, so that if the
411      callback from `free_waiting_entry()` happens to re-issue
412      the request, we don't immediately have it back in the
413      `waiting_map`. */
414   GNUNET_assert (GNUNET_OK ==
415                  GNUNET_CONTAINER_multipeermap_remove (cadet_map,
416                                                        &mh->target,
417                                                        mh));
418   GNUNET_CONTAINER_multihashmap_iterate (mh->waiting_map,
419                                          &free_waiting_entry,
420                                          mh);
421   if (NULL != mh->timeout_task)
422     GNUNET_SCHEDULER_cancel (mh->timeout_task);
423   if (NULL != mh->reset_task)
424     GNUNET_SCHEDULER_cancel (mh->reset_task);
425   GNUNET_assert (0 ==
426                  GNUNET_CONTAINER_multihashmap_size (mh->waiting_map));
427   GNUNET_CONTAINER_multihashmap_destroy (mh->waiting_map);
428   GNUNET_free (mh);
429 }
430
431
432 /**
433  * Function called whenever an MQ-channel's transmission window size changes.
434  *
435  * The first callback in an outgoing channel will be with a non-zero value
436  * and will mean the channel is connected to the destination.
437  *
438  * For an incoming channel it will be called immediately after the
439  * #GNUNET_CADET_ConnectEventHandler, also with a non-zero value.
440  *
441  * @param cls Channel closure.
442  * @param channel Connection to the other end (henceforth invalid).
443  * @param window_size New window size. If the is more messages than buffer size
444  *                    this value will be negative..
445  */
446 static void
447 window_change_cb (void *cls,
448                   const struct GNUNET_CADET_Channel *channel,
449                   int window_size)
450 {
451   /* FIXME: for flow control, implement? */
452 #if 0
453   /* Something like this instead of the GNUNET_MQ_notify_sent() in
454      transmit_pending() might be good (once the window change CB works...) */
455   if (0 < window_size) /* test needed? */
456     transmit_pending (mh);
457 #endif
458 }
459
460
461 /**
462  * We had a serious error, tear down and re-create cadet from scratch.
463  *
464  * @param mh cadet to reset
465  */
466 static void
467 reset_cadet (struct CadetHandle *mh)
468 {
469   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
470               "Resetting cadet channel to %s\n",
471               GNUNET_i2s (&mh->target));
472   GNUNET_CADET_channel_destroy (mh->channel);
473   mh->channel = NULL;
474   GNUNET_CONTAINER_multihashmap_iterate (mh->waiting_map,
475                                          &move_to_pending,
476                                          mh);
477   {
478     struct GNUNET_MQ_MessageHandler handlers[] = {
479       GNUNET_MQ_hd_var_size (reply,
480                              GNUNET_MESSAGE_TYPE_FS_CADET_REPLY,
481                              struct CadetReplyMessage,
482                              mh),
483       GNUNET_MQ_handler_end ()
484     };
485     struct GNUNET_HashCode port;
486
487     GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER,
488                         strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER),
489                         &port);
490     mh->channel = GNUNET_CADET_channel_creatE (cadet_handle,
491                                                mh,
492                                                &mh->target,
493                                                &port,
494                                                GNUNET_CADET_OPTION_RELIABLE,
495                                                &window_change_cb,
496                                                &disconnect_cb,
497                                                handlers);
498   }
499   transmit_pending (mh);
500 }
501
502
503 /**
504  * Task called when it is time to destroy an inactive cadet channel.
505  *
506  * @param cls the `struct CadetHandle` to tear down
507  */
508 static void
509 cadet_timeout (void *cls)
510 {
511   struct CadetHandle *mh = cls;
512   struct GNUNET_CADET_Channel *tun;
513
514   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
515               "Timeout on cadet channel to %s\n",
516               GNUNET_i2s (&mh->target));
517   mh->timeout_task = NULL;
518   tun = mh->channel;
519   mh->channel = NULL;
520   if (NULL != tun)
521     GNUNET_CADET_channel_destroy (tun);
522 }
523
524
525 /**
526  * Task called when it is time to reset an cadet.
527  *
528  * @param cls the `struct CadetHandle` to tear down
529  */
530 static void
531 reset_cadet_task (void *cls)
532 {
533   struct CadetHandle *mh = cls;
534
535   mh->reset_task = NULL;
536   reset_cadet (mh);
537 }
538
539
540 /**
541  * Transmit pending requests via the cadet.
542  *
543  * @param cls `struct CadetHandle` to process
544  */
545 static void
546 transmit_pending (void *cls)
547 {
548   struct CadetHandle *mh = cls;
549   struct GNUNET_MQ_Handle *mq = GNUNET_CADET_get_mq (mh->channel);
550   struct GSF_CadetRequest *sr;
551   struct GNUNET_MQ_Envelope *env;
552   struct CadetQueryMessage *sqm;
553
554   if ( (0 != GNUNET_MQ_get_length (mq)) ||
555        (NULL == (sr = mh->pending_head)) )
556     return;
557   GNUNET_CONTAINER_DLL_remove (mh->pending_head,
558                                mh->pending_tail,
559                                sr);
560   GNUNET_assert (GNUNET_OK ==
561                  GNUNET_CONTAINER_multihashmap_put (mh->waiting_map,
562                                                     &sr->query,
563                                                     sr,
564                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
565   sr->was_transmitted = GNUNET_YES;
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Sending query for %s via cadet to %s\n",
568               GNUNET_h2s (&sr->query),
569               GNUNET_i2s (&mh->target));
570   env = GNUNET_MQ_msg (sqm,
571                        GNUNET_MESSAGE_TYPE_FS_CADET_QUERY);
572   sqm->type = htonl (sr->type);
573   sqm->query = sr->query;
574   GNUNET_MQ_notify_sent (env,
575                          &transmit_pending,
576                          mh);
577   GNUNET_MQ_send (mq,
578                   env);
579 }
580
581
582 /**
583  * Get (or create) a cadet to talk to the given peer.
584  *
585  * @param target peer we want to communicate with
586  */
587 static struct CadetHandle *
588 get_cadet (const struct GNUNET_PeerIdentity *target)
589 {
590   struct CadetHandle *mh;
591
592   mh = GNUNET_CONTAINER_multipeermap_get (cadet_map,
593                                           target);
594   if (NULL != mh)
595   {
596     if (NULL != mh->timeout_task)
597     {
598       GNUNET_SCHEDULER_cancel (mh->timeout_task);
599       mh->timeout_task = NULL;
600     }
601     return mh;
602   }
603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
604               "Creating cadet channel to %s\n",
605               GNUNET_i2s (target));
606   mh = GNUNET_new (struct CadetHandle);
607   mh->reset_task = GNUNET_SCHEDULER_add_delayed (CLIENT_RETRY_TIMEOUT,
608                                                  &reset_cadet_task,
609                                                  mh);
610   mh->waiting_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_YES);
611   mh->target = *target;
612   GNUNET_assert (GNUNET_OK ==
613                  GNUNET_CONTAINER_multipeermap_put (cadet_map,
614                                                     &mh->target,
615                                                     mh,
616                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
617   {
618     struct GNUNET_MQ_MessageHandler handlers[] = {
619       GNUNET_MQ_hd_var_size (reply,
620                              GNUNET_MESSAGE_TYPE_FS_CADET_REPLY,
621                              struct CadetReplyMessage,
622                              mh),
623       GNUNET_MQ_handler_end ()
624     };
625     struct GNUNET_HashCode port;
626
627     GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER,
628                         strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER),
629                         &port);
630     mh->channel = GNUNET_CADET_channel_creatE (cadet_handle,
631                                                mh,
632                                                &mh->target,
633                                                &port,
634                                                GNUNET_CADET_OPTION_RELIABLE,
635                                                &window_change_cb,
636                                                &disconnect_cb,
637                                                handlers);
638   }
639   return mh;
640 }
641
642
643 /**
644  * Look for a block by directly contacting a particular peer.
645  *
646  * @param target peer that should have the block
647  * @param query hash to query for the block
648  * @param type desired type for the block
649  * @param proc function to call with result
650  * @param proc_cls closure for @a proc
651  * @return handle to cancel the operation
652  */
653 struct GSF_CadetRequest *
654 GSF_cadet_query (const struct GNUNET_PeerIdentity *target,
655                  const struct GNUNET_HashCode *query,
656                  enum GNUNET_BLOCK_Type type,
657                  GSF_CadetReplyProcessor proc,
658                  void *proc_cls)
659 {
660   struct CadetHandle *mh;
661   struct GSF_CadetRequest *sr;
662
663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
664               "Preparing to send query for %s via cadet to %s\n",
665               GNUNET_h2s (query),
666               GNUNET_i2s (target));
667   mh = get_cadet (target);
668   sr = GNUNET_new (struct GSF_CadetRequest);
669   sr->mh = mh;
670   sr->proc = proc;
671   sr->proc_cls = proc_cls;
672   sr->type = type;
673   sr->query = *query;
674   GNUNET_CONTAINER_DLL_insert (mh->pending_head,
675                                mh->pending_tail,
676                                sr);
677   transmit_pending (mh);
678   return sr;
679 }
680
681
682 /**
683  * Cancel an active request; must not be called after 'proc'
684  * was calld.
685  *
686  * @param sr request to cancel
687  */
688 void
689 GSF_cadet_query_cancel (struct GSF_CadetRequest *sr)
690 {
691   struct CadetHandle *mh = sr->mh;
692   GSF_CadetReplyProcessor p;
693
694   p = sr->proc;
695   sr->proc = NULL;
696   if (NULL != p)
697   {
698     /* signal failure / cancellation to callback */
699     p (sr->proc_cls, GNUNET_BLOCK_TYPE_ANY,
700        GNUNET_TIME_UNIT_ZERO_ABS,
701        0, NULL);
702   }
703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
704               "Cancelled query for %s via cadet to %s\n",
705               GNUNET_h2s (&sr->query),
706               GNUNET_i2s (&sr->mh->target));
707   if (GNUNET_YES == sr->was_transmitted)
708     GNUNET_assert (GNUNET_OK ==
709                    GNUNET_CONTAINER_multihashmap_remove (mh->waiting_map,
710                                                          &sr->query,
711                                                          sr));
712   else
713     GNUNET_CONTAINER_DLL_remove (mh->pending_head,
714                                  mh->pending_tail,
715                                  sr);
716   GNUNET_free (sr);
717   if ( (0 == GNUNET_CONTAINER_multihashmap_size (mh->waiting_map)) &&
718        (NULL == mh->pending_head) )
719     mh->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
720                                                      &cadet_timeout,
721                                                      mh);
722 }
723
724
725 /**
726  * Function called on each active cadets to shut them down.
727  *
728  * @param cls NULL
729  * @param key target peer, unused
730  * @param value the `struct CadetHandle` to destroy
731  * @return #GNUNET_YES (continue to iterate)
732  */
733 int
734 GSF_cadet_release_clients (void *cls,
735                            const struct GNUNET_PeerIdentity *key,
736                            void *value)
737 {
738   struct CadetHandle *mh = value;
739
740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
741               "Timeout on cadet channel to %s\n",
742               GNUNET_i2s (&mh->target));
743   if (NULL != mh->channel)
744     GNUNET_CADET_channel_destroy (mh->channel);
745   return GNUNET_YES;
746 }
747
748
749
750 /* end of gnunet-service-fs_cadet_client.c */