fix #4383
[oweals/gnunet.git] / src / rps / rps_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
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 rps/rps_api.c
23  * @brief API for rps
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "rps.h"
29 #include "gnunet_rps_service.h"
30
31 #include <inttypes.h>
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "rps-api",__VA_ARGS__)
34
35 /**
36  * Handler to handle requests from a client.
37  */
38 struct GNUNET_RPS_Handle
39 {
40   /**
41    * The handle to the client configuration.
42    */
43   const struct GNUNET_CONFIGURATION_Handle *cfg;
44
45   /**
46    * The message queue to the client.
47    */
48   struct GNUNET_MQ_Handle *mq;
49
50   /**
51    * Array of Request_Handles.
52    */
53   struct GNUNET_CONTAINER_MultiHashMap32 *req_handlers;
54
55   /**
56    * The id of the last request.
57    */
58   uint32_t current_request_id;
59 };
60
61
62 /**
63  * Handler to single requests from the client.
64  */
65 struct GNUNET_RPS_Request_Handle
66 {
67   /**
68    * The client issuing the request.
69    */
70   struct GNUNET_RPS_Handle *rps_handle;
71
72   /**
73    * The id of the request.
74    */
75   uint32_t id;
76
77   /**
78    * The callback to be called when we receive an answer.
79    */
80   GNUNET_RPS_NotifyReadyCB ready_cb;
81
82   /**
83    * The closure for the callback.
84    */
85   void *ready_cb_cls;
86 };
87
88
89 /**
90  * Struct used to pack the callback, its closure (provided by the caller)
91  * and the connection handler to the service to pass it to a callback function.
92  */
93 struct cb_cls_pack
94 {
95   /**
96    * Callback provided by the client
97    */
98   GNUNET_RPS_NotifyReadyCB cb;
99
100   /**
101    * Closure provided by the client
102    */
103   void *cls;
104
105   /**
106    * Handle to the service connection
107    */
108  struct GNUNET_CLIENT_Connection *service_conn;
109 };
110
111
112
113 /**
114  * This function is called, when the service replies to our request.
115  * It verifies that @a msg is well-formed.
116  *
117  * @param cls the closure
118  * @param msg the message
119  * @return #GNUNET_OK if @a msg is well-formed
120  */
121 static int
122 check_reply (void *cls,
123              const struct GNUNET_RPS_CS_ReplyMessage *msg)
124 {
125   uint16_t msize = ntohs (msg->header.size);
126   uint32_t num_peers = ntohl (msg->num_peers);
127
128   msize -= sizeof (struct GNUNET_RPS_CS_ReplyMessage);
129   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
130        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
131   {
132     GNUNET_break (0);
133     return GNUNET_SYSERR;
134   }
135   return GNUNET_OK;
136 }
137
138
139 /**
140  * This function is called, when the service replies to our request.
141  * It calls the callback the caller gave us with the provided closure
142  * and disconnects afterwards.
143  *
144  * @param cls the closure
145  * @param msg the message
146  */
147 static void
148 handle_reply (void *cls,
149               const struct GNUNET_RPS_CS_ReplyMessage *msg)
150 {
151   struct GNUNET_RPS_Handle *h = cls;
152   struct GNUNET_PeerIdentity *peers;
153   struct GNUNET_RPS_Request_Handle *rh;
154   uint32_t id;
155
156   /* Give the peers back */
157   id = ntohl (msg->id);
158   LOG (GNUNET_ERROR_TYPE_DEBUG,
159        "Service replied with %" PRIu32 " peers for id %" PRIu32 "\n",
160        ntohl (msg->num_peers),
161        id);
162
163   peers = (struct GNUNET_PeerIdentity *) &msg[1];
164   GNUNET_assert (GNUNET_YES ==
165       GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers, id));
166   rh = GNUNET_CONTAINER_multihashmap32_get (h->req_handlers, id);
167   GNUNET_assert (NULL != rh);
168   GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, id);
169   rh->ready_cb (rh->ready_cb_cls,
170                 ntohl (msg->num_peers),
171                 peers);
172 }
173
174
175 /**
176  * Reconnect to the service
177  */
178 static void
179 reconnect (struct GNUNET_RPS_Handle *h);
180
181
182 /**
183  * Error handler for mq.
184  *
185  * This function is called whan mq encounters an error.
186  * Until now mq doesn't provide useful error messages.
187  *
188  * @param cls the closure
189  * @param error error code without specyfied meaning
190  */
191 static void
192 mq_error_handler (void *cls,
193                   enum GNUNET_MQ_Error error)
194 {
195   struct GNUNET_RPS_Handle *h = cls;
196   //TODO LOG
197   LOG (GNUNET_ERROR_TYPE_WARNING, "Problem with message queue. error: %i\n\
198        1: READ,\n\
199        2: WRITE,\n\
200        4: TIMEOUT\n",
201        error);
202   reconnect (h);
203 }
204
205
206 /**
207  * Reconnect to the service
208  */
209 static void
210 reconnect (struct GNUNET_RPS_Handle *h)
211 {
212   struct GNUNET_MQ_MessageHandler mq_handlers[] = {
213     GNUNET_MQ_hd_var_size (reply,
214                            GNUNET_MESSAGE_TYPE_RPS_CS_REPLY,
215                            struct GNUNET_RPS_CS_ReplyMessage,
216                            h),
217     GNUNET_MQ_handler_end ()
218   };
219
220   if (NULL != h->mq)
221     GNUNET_MQ_destroy (h->mq);
222   h->mq = GNUNET_CLIENT_connecT (h->cfg,
223                                  "rps",
224                                  mq_handlers,
225                                  &mq_error_handler,
226                                  h);
227 }
228
229
230 /**
231  * Connect to the rps service
232  *
233  * @param cfg configuration to use
234  * @return a handle to the service
235  */
236 struct GNUNET_RPS_Handle *
237 GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
238 {
239   struct GNUNET_RPS_Handle *h;
240
241   h = GNUNET_new (struct GNUNET_RPS_Handle);
242   h->cfg = cfg;
243   reconnect (h);
244   if (NULL == h->mq)
245   {
246     GNUNET_free (h);
247     return NULL;
248   }
249   h->req_handlers = GNUNET_CONTAINER_multihashmap32_create (4);
250   return h;
251 }
252
253
254 /**
255  * Request n random peers.
256  *
257  * @param rps_handle handle to the rps service
258  * @param num_req_peers number of peers we want to receive
259  * @param ready_cb the callback called when the peers are available
260  * @param cls closure given to the callback
261  * @return a handle to cancel this request
262  */
263 struct GNUNET_RPS_Request_Handle *
264 GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *rps_handle,
265                           uint32_t num_req_peers,
266                           GNUNET_RPS_NotifyReadyCB ready_cb,
267                           void *cls)
268 {
269   struct GNUNET_RPS_Request_Handle *rh;
270   struct GNUNET_MQ_Envelope *ev;
271   struct GNUNET_RPS_CS_RequestMessage *msg;
272
273   // assert func != NULL
274   rh = GNUNET_new (struct GNUNET_RPS_Request_Handle);
275   rh->rps_handle = rps_handle;
276   rh->id = rps_handle->current_request_id++;
277   rh->ready_cb = ready_cb;
278   rh->ready_cb_cls = cls;
279
280   LOG (GNUNET_ERROR_TYPE_DEBUG,
281        "Requesting %" PRIu32 " peers with id %" PRIu32 "\n",
282        num_req_peers,
283        rh->id);
284
285   GNUNET_CONTAINER_multihashmap32_put (rps_handle->req_handlers, rh->id, rh,
286       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
287
288   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST);
289   msg->num_peers = htonl (num_req_peers);
290   msg->id = htonl (rh->id);
291   GNUNET_MQ_send (rps_handle->mq, ev);
292   return rh;
293 }
294
295
296 /**
297  * Seed rps service with peerIDs.
298  *
299  * @param h handle to the rps service
300  * @param n number of peers to seed
301  * @param ids the ids of the peers seeded
302  */
303 void
304 GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h,
305                      uint32_t n,
306                      const struct GNUNET_PeerIdentity *ids)
307 {
308   size_t size_needed;
309   uint32_t num_peers_max;
310   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
311   struct GNUNET_MQ_Envelope *ev;
312   struct GNUNET_RPS_CS_SeedMessage *msg;
313
314   unsigned int i;
315
316   LOG (GNUNET_ERROR_TYPE_DEBUG,
317        "Client wants to seed %" PRIu32 " peers:\n",
318        n);
319   for (i = 0 ; i < n ; i++)
320     LOG (GNUNET_ERROR_TYPE_DEBUG,
321          "%u. peer: %s\n",
322          i,
323          GNUNET_i2s (&ids[i]));
324
325   /* The actual size the message occupies */
326   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
327     n * sizeof (struct GNUNET_PeerIdentity);
328   /* The number of peers that fits in one message together with
329    * the respective header */
330   num_peers_max = (GNUNET_SERVER_MAX_MESSAGE_SIZE -
331       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
332     sizeof (struct GNUNET_PeerIdentity);
333   tmp_peer_pointer = ids;
334
335   while (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
336   {
337     ev = GNUNET_MQ_msg_extra (msg, num_peers_max * sizeof (struct GNUNET_PeerIdentity),
338         GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
339     msg->num_peers = htonl (num_peers_max);
340     GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers_max * sizeof (struct GNUNET_PeerIdentity));
341     GNUNET_MQ_send (h->mq, ev);
342
343     n -= num_peers_max;
344     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
345                   n * sizeof (struct GNUNET_PeerIdentity);
346     /* Set pointer to beginning of next block of num_peers_max peers */
347     tmp_peer_pointer = &ids[num_peers_max];
348   }
349
350   ev = GNUNET_MQ_msg_extra (msg, n * sizeof (struct GNUNET_PeerIdentity),
351                             GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
352   msg->num_peers = htonl (n);
353   GNUNET_memcpy (&msg[1], tmp_peer_pointer, n * sizeof (struct GNUNET_PeerIdentity));
354
355   GNUNET_MQ_send (h->mq, ev);
356 }
357
358
359 #ifdef ENABLE_MALICIOUS
360 /**
361  * Turn RPS service to act malicious.
362  *
363  * @param h handle to the rps service
364  * @param type which type of malicious peer to turn to.
365  *             0 Don't act malicious at all
366  *             1 Try to maximise representation
367  *             2 Try to partition the network
368  *               (isolate one peer from the rest)
369  * @param n number of @a ids
370  * @param ids the ids of the malicious peers
371  *            if @type is 2 the last id is the id of the
372  *            peer to be isolated from the rest
373  */
374 void
375 GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h,
376                           uint32_t type,
377                           uint32_t num_peers,
378                           const struct GNUNET_PeerIdentity *peer_ids,
379                           const struct GNUNET_PeerIdentity *target_peer)
380 {
381   size_t size_needed;
382   uint32_t num_peers_max;
383   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
384   struct GNUNET_MQ_Envelope *ev;
385   struct GNUNET_RPS_CS_ActMaliciousMessage *msg;
386
387   unsigned int i;
388
389   LOG (GNUNET_ERROR_TYPE_DEBUG,
390        "Client turns malicious (type %" PRIu32 ") with %" PRIu32 " other peers:\n",
391        type,
392        num_peers);
393   for (i = 0 ; i < num_peers ; i++)
394     LOG (GNUNET_ERROR_TYPE_DEBUG,
395          "%u. peer: %s\n",
396          i,
397          GNUNET_i2s (&peer_ids[i]));
398
399   /* The actual size the message would occupy */
400   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
401     num_peers * sizeof (struct GNUNET_PeerIdentity);
402   /* The number of peers that fit in one message together with
403    * the respective header */
404   num_peers_max = (GNUNET_SERVER_MAX_MESSAGE_SIZE -
405       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
406     sizeof (struct GNUNET_PeerIdentity);
407   tmp_peer_pointer = peer_ids;
408
409   while (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
410   {
411     LOG (GNUNET_ERROR_TYPE_DEBUG,
412          "Too many peers to send at once, sending %" PRIu32 " (all we can so far)\n",
413          num_peers_max);
414     ev = GNUNET_MQ_msg_extra (msg,
415                               num_peers_max * sizeof (struct GNUNET_PeerIdentity),
416                               GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
417     msg->type = htonl (type);
418     msg->num_peers = htonl (num_peers_max);
419     if ( (2 == type) ||
420          (3 == type) )
421       msg->attacked_peer = peer_ids[num_peers];
422     GNUNET_memcpy (&msg[1],
423             tmp_peer_pointer,
424             num_peers_max * sizeof (struct GNUNET_PeerIdentity));
425
426     GNUNET_MQ_send (h->mq, ev);
427
428     num_peers -= num_peers_max;
429     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
430                   num_peers * sizeof (struct GNUNET_PeerIdentity);
431     /* Set pointer to beginning of next block of num_peers_max peers */
432     tmp_peer_pointer = &peer_ids[num_peers_max];
433   }
434
435   ev = GNUNET_MQ_msg_extra (msg,
436                             num_peers * sizeof (struct GNUNET_PeerIdentity),
437                             GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
438   msg->type = htonl (type);
439   msg->num_peers = htonl (num_peers);
440   if ( (2 == type) ||
441        (3 == type) )
442     msg->attacked_peer = *target_peer;
443   GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers * sizeof (struct GNUNET_PeerIdentity));
444
445   GNUNET_MQ_send (h->mq, ev);
446 }
447 #endif /* ENABLE_MALICIOUS */
448
449
450 /**
451  * Cancle an issued request.
452  *
453  * @param rh request handle of request to cancle
454  */
455 void
456 GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh)
457 {
458   struct GNUNET_RPS_Handle *h;
459   struct GNUNET_MQ_Envelope *ev;
460   struct GNUNET_RPS_CS_RequestCancelMessage*msg;
461
462   LOG (GNUNET_ERROR_TYPE_DEBUG,
463        "Cancelling request with id %" PRIu32 "\n",
464        rh->id);
465
466   h = rh->rps_handle;
467   GNUNET_assert (GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers,
468         rh->id));
469   GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, rh->id);
470   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL);
471   msg->id = htonl (rh->id);
472   GNUNET_MQ_send (rh->rps_handle->mq, ev);
473 }
474
475
476 /**
477  * Disconnect from the rps service
478  *
479  * @param h the handle to the rps service
480  */
481 void
482 GNUNET_RPS_disconnect (struct GNUNET_RPS_Handle *h)
483 {
484   GNUNET_MQ_destroy (h->mq);
485   if (0 < GNUNET_CONTAINER_multihashmap32_size (h->req_handlers))
486     LOG (GNUNET_ERROR_TYPE_WARNING,
487         "Still waiting for requests\n");
488   GNUNET_CONTAINER_multihashmap32_destroy (h->req_handlers);
489   GNUNET_free (h);
490 }
491
492
493 /* end of rps_api.c */