indentation, comment and style fixes, no semantic changes
[oweals/gnunet.git] / src / fs / gnunet-service-fs_cadet_server.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013, 2017 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_server.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  * After how long do we termiante idle connections?
42  */
43 #define IDLE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
44
45
46 /**
47  * A message in the queue to be written to the cadet.
48  */
49 struct WriteQueueItem
50 {
51   /**
52    * Kept in a DLL.
53    */
54   struct WriteQueueItem *next;
55
56   /**
57    * Kept in a DLL.
58    */
59   struct WriteQueueItem *prev;
60
61   /**
62    * Number of bytes of payload, allocated at the end of this struct.
63    */
64   size_t msize;
65 };
66
67
68 /**
69  * Information we keep around for each active cadeting client.
70  */
71 struct CadetClient
72 {
73   /**
74    * DLL
75    */
76   struct CadetClient *next;
77
78   /**
79    * DLL
80    */
81   struct CadetClient *prev;
82
83   /**
84    * Channel for communication.
85    */
86   struct GNUNET_CADET_Channel *channel;
87
88   /**
89    * Head of write queue.
90    */
91   struct WriteQueueItem *wqi_head;
92
93   /**
94    * Tail of write queue.
95    */
96   struct WriteQueueItem *wqi_tail;
97
98   /**
99    * Current active request to the datastore, if we have one pending.
100    */
101   struct GNUNET_DATASTORE_QueueEntry *qe;
102
103   /**
104    * Task that is scheduled to asynchronously terminate the connection.
105    */
106   struct GNUNET_SCHEDULER_Task * terminate_task;
107
108   /**
109    * Task that is scheduled to terminate idle connections.
110    */
111   struct GNUNET_SCHEDULER_Task * timeout_task;
112
113   /**
114    * Size of the last write that was initiated.
115    */
116   size_t reply_size;
117
118 };
119
120
121 /**
122  * Listen port for incoming requests.
123  */
124 static struct GNUNET_CADET_Port *cadet_port;
125
126 /**
127  * Head of DLL of cadet clients.
128  */
129 static struct CadetClient *sc_head;
130
131 /**
132  * Tail of DLL of cadet clients.
133  */
134 static struct CadetClient *sc_tail;
135
136 /**
137  * Number of active cadet clients in the 'sc_*'-DLL.
138  */
139 static unsigned int sc_count;
140
141 /**
142  * Maximum allowed number of cadet clients.
143  */
144 static unsigned long long sc_count_max;
145
146
147
148 /**
149  * Task run to asynchronously terminate the cadet due to timeout.
150  *
151  * @param cls the 'struct CadetClient'
152  */
153 static void
154 timeout_cadet_task (void *cls)
155 {
156   struct CadetClient *sc = cls;
157   struct GNUNET_CADET_Channel *tun;
158
159   sc->timeout_task = NULL;
160   tun = sc->channel;
161   sc->channel = NULL;
162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
163               "Timeout for inactive cadet client %p\n",
164               sc);
165   GNUNET_CADET_channel_destroy (tun);
166 }
167
168
169 /**
170  * Reset the timeout for the cadet client (due to activity).
171  *
172  * @param sc client handle to reset timeout for
173  */
174 static void
175 refresh_timeout_task (struct CadetClient *sc)
176 {
177   if (NULL != sc->timeout_task)
178     GNUNET_SCHEDULER_cancel (sc->timeout_task);
179   sc->timeout_task = GNUNET_SCHEDULER_add_delayed (IDLE_TIMEOUT,
180                                                    &timeout_cadet_task,
181                                                    sc);
182 }
183
184
185 /**
186  * Check if we are done with the write queue, and if so tell CADET
187  * that we are ready to read more.
188  *
189  * @param cls where to process the write queue
190  */
191 static void
192 continue_writing (void *cls)
193 {
194   struct CadetClient *sc = cls;
195   struct GNUNET_MQ_Handle *mq;
196
197   mq = GNUNET_CADET_get_mq (sc->channel);
198   if (0 != GNUNET_MQ_get_length (mq))
199   {
200     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
201                 "Write pending, waiting for it to complete\n");
202     return;
203   }
204   refresh_timeout_task (sc);
205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
206               "Finished processing cadet request from client %p, ready to receive the next one\n",
207               sc);
208   GNUNET_CADET_receive_done (sc->channel);
209 }
210
211
212 /**
213  * Process a datum that was stored in the datastore.
214  *
215  * @param cls closure with the `struct CadetClient` which sent the query
216  * @param key key for the content
217  * @param size number of bytes in @a data
218  * @param data content stored
219  * @param type type of the content
220  * @param priority priority of the content
221  * @param anonymity anonymity-level for the content
222  * @param expiration expiration time for the content
223  * @param uid unique identifier for the datum;
224  *        maybe 0 if no unique identifier is available
225  */
226 static void
227 handle_datastore_reply (void *cls,
228                         const struct GNUNET_HashCode *key,
229                         size_t size,
230                         const void *data,
231                         enum GNUNET_BLOCK_Type type,
232                         uint32_t priority,
233                         uint32_t anonymity,
234                         struct GNUNET_TIME_Absolute expiration,
235                         uint64_t uid)
236 {
237   struct CadetClient *sc = cls;
238   size_t msize = size + sizeof (struct CadetReplyMessage);
239   struct GNUNET_MQ_Envelope *env;
240   struct CadetReplyMessage *srm;
241
242   sc->qe = NULL;
243   if (NULL == data)
244   {
245     /* no result, this should not really happen, as for
246        non-anonymous routing only peers that HAVE the
247        answers should be queried; OTOH, this is not a
248        hard error as we might have had the answer in the
249        past and the user might have unindexed it. Hence
250        we log at level "INFO" for now. */
251     if (NULL == key)
252     {
253       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
254                   "Have no answer and the query was NULL\n");
255     }
256     else
257     {
258       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
259                   "Have no answer for query `%s'\n",
260                   GNUNET_h2s (key));
261     }
262     GNUNET_STATISTICS_update (GSF_stats,
263                               gettext_noop ("# queries received via CADET not answered"),
264                               1,
265                               GNUNET_NO);
266     continue_writing (sc);
267     return;
268   }
269   if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type)
270   {
271     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
272                 "Performing on-demand encoding for query %s\n",
273                 GNUNET_h2s (key));
274     if (GNUNET_OK !=
275         GNUNET_FS_handle_on_demand_block (key,
276                                           size,
277                                           data,
278                                           type,
279                                           priority,
280                                           anonymity,
281                                           expiration,
282                                           uid,
283                                           &handle_datastore_reply,
284                                           sc))
285     {
286       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
287                   "On-demand encoding request failed\n");
288       continue_writing (sc);
289     }
290     return;
291   }
292   if (msize > GNUNET_SERVER_MAX_MESSAGE_SIZE)
293   {
294     GNUNET_break (0);
295     continue_writing (sc);
296     return;
297   }
298   GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type);
299   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
300               "Starting transmission of %u byte reply of type %d for query `%s' via cadet to %p\n",
301               (unsigned int) size,
302               (unsigned int) type,
303               GNUNET_h2s (key),
304               sc);
305   env = GNUNET_MQ_msg_extra (srm,
306                              size,
307                              GNUNET_MESSAGE_TYPE_FS_CADET_REPLY);
308   srm->type = htonl (type);
309   srm->expiration = GNUNET_TIME_absolute_hton (expiration);
310   GNUNET_memcpy (&srm[1],
311                  data,
312                  size);
313   GNUNET_MQ_notify_sent (env,
314                          &continue_writing,
315                          sc);
316   GNUNET_STATISTICS_update (GSF_stats,
317                             gettext_noop ("# Blocks transferred via cadet"),
318                             1,
319                             GNUNET_NO);
320   GNUNET_MQ_send (GNUNET_CADET_get_mq (sc->channel),
321                   env);
322 }
323
324
325 /**
326  * Functions with this signature are called whenever a
327  * complete query message is received.
328  *
329  * @param cls closure with the `struct CadetClient`
330  * @param sqm the actual message
331  */
332 static void
333 handle_request (void *cls,
334                 const struct CadetQueryMessage *sqm)
335 {
336   struct CadetClient *sc = cls;
337
338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
339               "Received query for `%s' via cadet from client %p\n",
340               GNUNET_h2s (&sqm->query),
341               sc);
342   GNUNET_STATISTICS_update (GSF_stats,
343                             gettext_noop ("# queries received via cadet"),
344                             1,
345                             GNUNET_NO);
346   refresh_timeout_task (sc);
347   sc->qe = GNUNET_DATASTORE_get_key (GSF_dsh,
348                                      0,
349                                      &sqm->query,
350                                      ntohl (sqm->type),
351                                      0 /* priority */,
352                                      GSF_datastore_queue_size,
353                                      &handle_datastore_reply,
354                                      sc);
355   if (NULL == sc->qe)
356   {
357     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
358                 "Queueing request with datastore failed (queue full?)\n");
359     continue_writing (sc);
360   }
361 }
362
363
364 /**
365  * Functions of this type are called upon new cadet connection from other peers.
366  *
367  * @param cls the closure from GNUNET_CADET_connect
368  * @param channel the channel representing the cadet
369  * @param initiator the identity of the peer who wants to establish a cadet
370  *            with us; NULL on binding error
371  * @return initial channel context (our `struct CadetClient`)
372  */
373 static void *
374 connect_cb (void *cls,
375             struct GNUNET_CADET_Channel *channel,
376             const struct GNUNET_PeerIdentity *initiator)
377 {
378   struct CadetClient *sc;
379
380   GNUNET_assert (NULL != channel);
381   if (sc_count >= sc_count_max)
382   {
383     GNUNET_STATISTICS_update (GSF_stats,
384                               gettext_noop ("# cadet client connections rejected"),
385                               1,
386                               GNUNET_NO);
387     GNUNET_CADET_channel_destroy (channel);
388     return NULL;
389   }
390   GNUNET_STATISTICS_update (GSF_stats,
391                             gettext_noop ("# cadet connections active"),
392                             1,
393                             GNUNET_NO);
394   sc = GNUNET_new (struct CadetClient);
395   sc->channel = channel;
396   GNUNET_CONTAINER_DLL_insert (sc_head,
397                                sc_tail,
398                                sc);
399   sc_count++;
400   refresh_timeout_task (sc);
401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
402               "Accepting inbound cadet connection from `%s' as client %p\n",
403               GNUNET_i2s (initiator),
404               sc);
405   return sc;
406 }
407
408
409 /**
410  * Function called by cadet when a client disconnects.
411  * Cleans up our `struct CadetClient` of that channel.
412  *
413  * @param cls  our `struct CadetClient`
414  * @param channel channel of the disconnecting client
415  * @param channel_ctx
416  */
417 static void
418 disconnect_cb (void *cls,
419                const struct GNUNET_CADET_Channel *channel)
420 {
421   struct CadetClient *sc = cls;
422   struct WriteQueueItem *wqi;
423
424   if (NULL == sc)
425     return;
426   sc->channel = NULL;
427   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
428               "Terminating cadet connection with client %p\n",
429               sc);
430   GNUNET_STATISTICS_update (GSF_stats,
431                             gettext_noop ("# cadet connections active"), -1,
432                             GNUNET_NO);
433   if (NULL != sc->terminate_task)
434     GNUNET_SCHEDULER_cancel (sc->terminate_task);
435   if (NULL != sc->timeout_task)
436     GNUNET_SCHEDULER_cancel (sc->timeout_task);
437   if (NULL != sc->qe)
438     GNUNET_DATASTORE_cancel (sc->qe);
439   while (NULL != (wqi = sc->wqi_head))
440   {
441     GNUNET_CONTAINER_DLL_remove (sc->wqi_head,
442                                  sc->wqi_tail,
443                                  wqi);
444     GNUNET_free (wqi);
445   }
446   GNUNET_CONTAINER_DLL_remove (sc_head,
447                                sc_tail,
448                                sc);
449   sc_count--;
450   GNUNET_free (sc);
451 }
452
453
454 /**
455  * Function called whenever an MQ-channel's transmission window size changes.
456  *
457  * The first callback in an outgoing channel will be with a non-zero value
458  * and will mean the channel is connected to the destination.
459  *
460  * For an incoming channel it will be called immediately after the
461  * #GNUNET_CADET_ConnectEventHandler, also with a non-zero value.
462  *
463  * @param cls Channel closure.
464  * @param channel Connection to the other end (henceforth invalid).
465  * @param window_size New window size. If the is more messages than buffer size
466  *                    this value will be negative..
467  */
468 static void
469 window_change_cb (void *cls,
470                   const struct GNUNET_CADET_Channel *channel,
471                   int window_size)
472 {
473   /* FIXME: could do flow control here... */
474 }
475
476
477 /**
478  * Initialize subsystem for non-anonymous file-sharing.
479  */
480 void
481 GSF_cadet_start_server ()
482 {
483   struct GNUNET_MQ_MessageHandler handlers[] = {
484     GNUNET_MQ_hd_fixed_size (request,
485                              GNUNET_MESSAGE_TYPE_FS_CADET_QUERY,
486                              struct CadetQueryMessage,
487                              NULL),
488     GNUNET_MQ_handler_end ()
489   };
490   struct GNUNET_HashCode port;
491
492   if (GNUNET_YES !=
493       GNUNET_CONFIGURATION_get_value_number (GSF_cfg,
494                                              "fs",
495                                              "MAX_CADET_CLIENTS",
496                                              &sc_count_max))
497     return;
498   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
499               "Initializing cadet FS server with a limit of %llu connections\n",
500               sc_count_max);
501   cadet_map = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES);
502   cadet_handle = GNUNET_CADET_connecT (GSF_cfg);
503   GNUNET_assert (NULL != cadet_handle);
504   GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER,
505                       strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER),
506                       &port);
507   cadet_port = GNUNET_CADET_open_porT (cadet_handle,
508                                        &port,
509                                        &connect_cb,
510                                        NULL,
511                                        &window_change_cb,
512                                        &disconnect_cb,
513                                        handlers);
514 }
515
516
517 /**
518  * Shutdown subsystem for non-anonymous file-sharing.
519  */
520 void
521 GSF_cadet_stop_server ()
522 {
523   GNUNET_CONTAINER_multipeermap_iterate (cadet_map,
524                                          &GSF_cadet_release_clients,
525                                          NULL);
526   GNUNET_CONTAINER_multipeermap_destroy (cadet_map);
527   cadet_map = NULL;
528   if (NULL != cadet_port)
529   {
530     GNUNET_CADET_close_port (cadet_port);
531     cadet_port = NULL;
532   }
533   if (NULL != cadet_handle)
534   {
535     GNUNET_CADET_disconnect (cadet_handle);
536     cadet_handle = NULL;
537   }
538   GNUNET_assert (NULL == sc_head);
539   GNUNET_assert (0 == sc_count);
540 }
541
542 /* end of gnunet-service-fs_cadet.c */