0da3bd4a4a43b3c5a8f45ba56f3a0d7011069d0d
[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    * @brief Callback called on each update of the view
62    */
63   GNUNET_RPS_ViewUpdateCB view_update_cb;
64
65   /**
66    * @brief Callback called on each update of the view
67    */
68   void *view_update_cls;
69 };
70
71
72 /**
73  * Handler to single requests from the client.
74  */
75 struct GNUNET_RPS_Request_Handle
76 {
77   /**
78    * The client issuing the request.
79    */
80   struct GNUNET_RPS_Handle *rps_handle;
81
82   /**
83    * The id of the request.
84    */
85   uint32_t id;
86
87   /**
88    * The number of requested peers.
89    */
90   uint32_t num_peers;
91
92   /**
93    * The callback to be called when we receive an answer.
94    */
95   GNUNET_RPS_NotifyReadyCB ready_cb;
96
97   /**
98    * The closure for the callback.
99    */
100   void *ready_cb_cls;
101 };
102
103
104 /**
105  * Struct used to pack the callback, its closure (provided by the caller)
106  * and the connection handler to the service to pass it to a callback function.
107  */
108 struct cb_cls_pack
109 {
110   /**
111    * Callback provided by the client
112    */
113   GNUNET_RPS_NotifyReadyCB cb;
114
115   /**
116    * Closure provided by the client
117    */
118   void *cls;
119
120   /**
121    * Handle to the service connection
122    */
123  struct GNUNET_CLIENT_Connection *service_conn;
124 };
125
126 /**
127  * @brief Send a request to the service.
128  *
129  * @param h rps handle
130  * @param id id of the request
131  * @param num_req_peers number of peers
132  */
133 void
134 send_request (const struct GNUNET_RPS_Handle *h,
135               uint32_t id,
136               uint32_t num_req_peers)
137 {
138   struct GNUNET_MQ_Envelope *ev;
139   struct GNUNET_RPS_CS_RequestMessage *msg;
140
141   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST);
142   msg->num_peers = htonl (num_req_peers);
143   msg->id = htonl (id);
144   GNUNET_MQ_send (h->mq, ev);
145 }
146
147 /**
148  * @brief Iterator function over pending requests
149  *
150  * Implements #GNUNET_CONTAINER_HashMapIterator32
151  *
152  * @param cls rps handle
153  * @param key id of the request
154  * @param value request handle
155  *
156  * @return GNUNET_YES to continue iteration
157  */
158 int
159 resend_requests_iterator (void *cls, uint32_t key, void *value)
160 {
161   const struct GNUNET_RPS_Handle *h = cls;
162   const struct GNUNET_RPS_Request_Handle *req_handle = value;
163
164   send_request (h, req_handle->id, req_handle->num_peers);
165   return GNUNET_YES; /* continue iterating */
166 }
167
168 /**
169  * @brief Resend all pending requests
170  *
171  * This is used to resend all pending requests after the client
172  * reconnected to the service, because the service cancels all
173  * pending requests after reconnection.
174  *
175  * @param h rps handle
176  */
177 void
178 resend_requests (struct GNUNET_RPS_Handle *h)
179 {
180   GNUNET_CONTAINER_multihashmap32_iterate (h->req_handlers,
181                                            resend_requests_iterator,
182                                            h);
183 }
184
185
186 /**
187  * This function is called, when the service replies to our request.
188  * It verifies that @a msg is well-formed.
189  *
190  * @param cls the closure
191  * @param msg the message
192  * @return #GNUNET_OK if @a msg is well-formed
193  */
194 static int
195 check_reply (void *cls,
196              const struct GNUNET_RPS_CS_ReplyMessage *msg)
197 {
198   uint16_t msize = ntohs (msg->header.size);
199   uint32_t num_peers = ntohl (msg->num_peers);
200
201   msize -= sizeof (struct GNUNET_RPS_CS_ReplyMessage);
202   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
203        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
204   {
205     GNUNET_break (0);
206     return GNUNET_SYSERR;
207   }
208   return GNUNET_OK;
209 }
210
211
212 /**
213  * This function is called, when the service replies to our request.
214  * It calls the callback the caller gave us with the provided closure
215  * and disconnects afterwards.
216  *
217  * @param cls the closure
218  * @param msg the message
219  */
220 static void
221 handle_reply (void *cls,
222               const struct GNUNET_RPS_CS_ReplyMessage *msg)
223 {
224   struct GNUNET_RPS_Handle *h = cls;
225   struct GNUNET_PeerIdentity *peers;
226   struct GNUNET_RPS_Request_Handle *rh;
227   uint32_t id;
228
229   /* Give the peers back */
230   id = ntohl (msg->id);
231   LOG (GNUNET_ERROR_TYPE_DEBUG,
232        "Service replied with %" PRIu32 " peers for id %" PRIu32 "\n",
233        ntohl (msg->num_peers),
234        id);
235
236   peers = (struct GNUNET_PeerIdentity *) &msg[1];
237   GNUNET_assert (GNUNET_YES ==
238       GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers, id));
239   rh = GNUNET_CONTAINER_multihashmap32_get (h->req_handlers, id);
240   GNUNET_assert (NULL != rh);
241   GNUNET_assert (rh->num_peers == ntohl (msg->num_peers));
242   GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, id);
243   rh->ready_cb (rh->ready_cb_cls,
244                 ntohl (msg->num_peers),
245                 peers);
246 }
247
248
249 /* Get internals for debugging/profiling purposes */
250
251 /**
252  * Request updates of view
253  *
254  * @param rps_handle handle to the rps service
255  * @param num_req_peers number of peers we want to receive
256  *        (0 for infinite updates)
257  * @param cls a closure that will be given to the callback
258  * @param ready_cb the callback called when the peers are available
259  */
260 void
261 GNUNET_RPS_view_request (struct GNUNET_RPS_Handle *rps_handle,
262                          uint32_t num_updates,
263                          GNUNET_RPS_ViewUpdateCB view_update_cb,
264                          void *cls)
265 {
266   struct GNUNET_MQ_Envelope *ev;
267   struct GNUNET_RPS_CS_DEBUG_ViewRequest *msg;
268
269   LOG (GNUNET_ERROR_TYPE_DEBUG,
270        "Client requests %" PRIu32 " view updates\n",
271        num_updates);
272   rps_handle->view_update_cb = view_update_cb;
273   rps_handle->view_update_cls = cls;
274
275   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REQUEST);
276   msg->num_updates = htonl (num_updates);
277   GNUNET_MQ_send (rps_handle->mq, ev);
278 }
279
280 /**
281  * This function is called, when the service updates the view.
282  * It verifies that @a msg is well-formed.
283  *
284  * @param cls the closure
285  * @param msg the message
286  * @return #GNUNET_OK if @a msg is well-formed
287  */
288 static int
289 check_view_update (void *cls,
290                    const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
291 {
292   uint16_t msize = ntohs (msg->header.size);
293   uint32_t num_peers = ntohl (msg->num_peers);
294
295   msize -= sizeof (struct GNUNET_RPS_CS_DEBUG_ViewReply);
296   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
297        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
298   {
299     GNUNET_break (0);
300     return GNUNET_SYSERR;
301   }
302   return GNUNET_OK;
303 }
304
305 /**
306  * This function is called, when the service updated its view.
307  * It calls the callback the caller provided
308  * and disconnects afterwards.
309  *
310  * @param msg the message
311  */
312 static void
313 handle_view_update (void *cls,
314                     const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
315 {
316   struct GNUNET_RPS_Handle *h = cls;
317   struct GNUNET_PeerIdentity *peers;
318
319   /* Give the peers back */
320   LOG (GNUNET_ERROR_TYPE_DEBUG,
321        "New view of %" PRIu32 " peers:\n",
322        ntohl (msg->num_peers));
323
324   peers = (struct GNUNET_PeerIdentity *) &msg[1];
325   GNUNET_assert (NULL != h);
326   GNUNET_assert (NULL != h->view_update_cb);
327   h->view_update_cb (h->view_update_cls, ntohl (msg->num_peers), peers);
328 }
329
330
331
332 /**
333  * Reconnect to the service
334  */
335 static void
336 reconnect (struct GNUNET_RPS_Handle *h);
337
338
339 /**
340  * Error handler for mq.
341  *
342  * This function is called whan mq encounters an error.
343  * Until now mq doesn't provide useful error messages.
344  *
345  * @param cls the closure
346  * @param error error code without specyfied meaning
347  */
348 static void
349 mq_error_handler (void *cls,
350                   enum GNUNET_MQ_Error error)
351 {
352   struct GNUNET_RPS_Handle *h = cls;
353   //TODO LOG
354   LOG (GNUNET_ERROR_TYPE_WARNING, "Problem with message queue. error: %i\n\
355        1: READ,\n\
356        2: WRITE,\n\
357        4: TIMEOUT\n",
358        error);
359   reconnect (h);
360   /* Resend all pending request as the service destroyed its knowledge
361    * about them */
362   resend_requests (h);
363 }
364
365
366 /**
367  * Reconnect to the service
368  */
369 static void
370 reconnect (struct GNUNET_RPS_Handle *h)
371 {
372   struct GNUNET_MQ_MessageHandler mq_handlers[] = {
373     GNUNET_MQ_hd_var_size (reply,
374                            GNUNET_MESSAGE_TYPE_RPS_CS_REPLY,
375                            struct GNUNET_RPS_CS_ReplyMessage,
376                            h),
377     GNUNET_MQ_hd_var_size (view_update,
378                            GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REPLY,
379                            struct GNUNET_RPS_CS_DEBUG_ViewReply,
380                            h),
381     GNUNET_MQ_handler_end ()
382   };
383
384   if (NULL != h->mq)
385     GNUNET_MQ_destroy (h->mq);
386   h->mq = GNUNET_CLIENT_connect (h->cfg,
387                                  "rps",
388                                  mq_handlers,
389                                  &mq_error_handler,
390                                  h);
391 }
392
393
394 /**
395  * Connect to the rps service
396  *
397  * @param cfg configuration to use
398  * @return a handle to the service
399  */
400 struct GNUNET_RPS_Handle *
401 GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
402 {
403   struct GNUNET_RPS_Handle *h;
404
405   h = GNUNET_new (struct GNUNET_RPS_Handle);
406   h->current_request_id = 0;
407   h->cfg = cfg;
408   reconnect (h);
409   if (NULL == h->mq)
410   {
411     GNUNET_free (h);
412     return NULL;
413   }
414   h->req_handlers = GNUNET_CONTAINER_multihashmap32_create (4);
415   return h;
416 }
417
418
419 /**
420  * Request n random peers.
421  *
422  * @param rps_handle handle to the rps service
423  * @param num_req_peers number of peers we want to receive
424  * @param ready_cb the callback called when the peers are available
425  * @param cls closure given to the callback
426  * @return a handle to cancel this request
427  */
428 struct GNUNET_RPS_Request_Handle *
429 GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *rps_handle,
430                           uint32_t num_req_peers,
431                           GNUNET_RPS_NotifyReadyCB ready_cb,
432                           void *cls)
433 {
434   struct GNUNET_RPS_Request_Handle *rh;
435
436   rh = GNUNET_new (struct GNUNET_RPS_Request_Handle);
437   rh->rps_handle = rps_handle;
438   rh->id = rps_handle->current_request_id++;
439   rh->num_peers = num_req_peers;
440   rh->ready_cb = ready_cb;
441   rh->ready_cb_cls = cls;
442
443   LOG (GNUNET_ERROR_TYPE_DEBUG,
444        "Requesting %" PRIu32 " peers with id %" PRIu32 "\n",
445        num_req_peers,
446        rh->id);
447
448   GNUNET_CONTAINER_multihashmap32_put (rps_handle->req_handlers, rh->id, rh,
449       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
450
451   send_request (rps_handle, rh->id, num_req_peers);
452   return rh;
453 }
454
455
456 /**
457  * Seed rps service with peerIDs.
458  *
459  * @param h handle to the rps service
460  * @param n number of peers to seed
461  * @param ids the ids of the peers seeded
462  */
463 void
464 GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h,
465                      uint32_t n,
466                      const struct GNUNET_PeerIdentity *ids)
467 {
468   size_t size_needed;
469   uint32_t num_peers_max;
470   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
471   struct GNUNET_MQ_Envelope *ev;
472   struct GNUNET_RPS_CS_SeedMessage *msg;
473
474   unsigned int i;
475
476   LOG (GNUNET_ERROR_TYPE_DEBUG,
477        "Client wants to seed %" PRIu32 " peers:\n",
478        n);
479   for (i = 0 ; i < n ; i++)
480     LOG (GNUNET_ERROR_TYPE_DEBUG,
481          "%u. peer: %s\n",
482          i,
483          GNUNET_i2s (&ids[i]));
484
485   /* The actual size the message occupies */
486   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
487     n * sizeof (struct GNUNET_PeerIdentity);
488   /* The number of peers that fits in one message together with
489    * the respective header */
490   num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
491       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
492     sizeof (struct GNUNET_PeerIdentity);
493   tmp_peer_pointer = ids;
494
495   while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
496   {
497     ev = GNUNET_MQ_msg_extra (msg, num_peers_max * sizeof (struct GNUNET_PeerIdentity),
498         GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
499     msg->num_peers = htonl (num_peers_max);
500     GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers_max * sizeof (struct GNUNET_PeerIdentity));
501     GNUNET_MQ_send (h->mq, ev);
502
503     n -= num_peers_max;
504     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
505                   n * sizeof (struct GNUNET_PeerIdentity);
506     /* Set pointer to beginning of next block of num_peers_max peers */
507     tmp_peer_pointer = &ids[num_peers_max];
508   }
509
510   ev = GNUNET_MQ_msg_extra (msg, n * sizeof (struct GNUNET_PeerIdentity),
511                             GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
512   msg->num_peers = htonl (n);
513   GNUNET_memcpy (&msg[1], tmp_peer_pointer, n * sizeof (struct GNUNET_PeerIdentity));
514
515   GNUNET_MQ_send (h->mq, ev);
516 }
517
518
519 #ifdef ENABLE_MALICIOUS
520 /**
521  * Turn RPS service to act malicious.
522  *
523  * @param h handle to the rps service
524  * @param type which type of malicious peer to turn to.
525  *             0 Don't act malicious at all
526  *             1 Try to maximise representation
527  *             2 Try to partition the network
528  *               (isolate one peer from the rest)
529  * @param n number of @a ids
530  * @param ids the ids of the malicious peers
531  *            if @type is 2 the last id is the id of the
532  *            peer to be isolated from the rest
533  */
534 void
535 GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h,
536                           uint32_t type,
537                           uint32_t num_peers,
538                           const struct GNUNET_PeerIdentity *peer_ids,
539                           const struct GNUNET_PeerIdentity *target_peer)
540 {
541   size_t size_needed;
542   uint32_t num_peers_max;
543   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
544   struct GNUNET_MQ_Envelope *ev;
545   struct GNUNET_RPS_CS_ActMaliciousMessage *msg;
546
547   unsigned int i;
548
549   LOG (GNUNET_ERROR_TYPE_DEBUG,
550        "Client turns malicious (type %" PRIu32 ") with %" PRIu32 " other peers:\n",
551        type,
552        num_peers);
553   for (i = 0 ; i < num_peers ; i++)
554     LOG (GNUNET_ERROR_TYPE_DEBUG,
555          "%u. peer: %s\n",
556          i,
557          GNUNET_i2s (&peer_ids[i]));
558
559   /* The actual size the message would occupy */
560   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
561     num_peers * sizeof (struct GNUNET_PeerIdentity);
562   /* The number of peers that fit in one message together with
563    * the respective header */
564   num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
565       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
566     sizeof (struct GNUNET_PeerIdentity);
567   tmp_peer_pointer = peer_ids;
568
569   while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
570   {
571     LOG (GNUNET_ERROR_TYPE_DEBUG,
572          "Too many peers to send at once, sending %" PRIu32 " (all we can so far)\n",
573          num_peers_max);
574     ev = GNUNET_MQ_msg_extra (msg,
575                               num_peers_max * sizeof (struct GNUNET_PeerIdentity),
576                               GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
577     msg->type = htonl (type);
578     msg->num_peers = htonl (num_peers_max);
579     if ( (2 == type) ||
580          (3 == type) )
581       msg->attacked_peer = peer_ids[num_peers];
582     GNUNET_memcpy (&msg[1],
583             tmp_peer_pointer,
584             num_peers_max * sizeof (struct GNUNET_PeerIdentity));
585
586     GNUNET_MQ_send (h->mq, ev);
587
588     num_peers -= num_peers_max;
589     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
590                   num_peers * sizeof (struct GNUNET_PeerIdentity);
591     /* Set pointer to beginning of next block of num_peers_max peers */
592     tmp_peer_pointer = &peer_ids[num_peers_max];
593   }
594
595   ev = GNUNET_MQ_msg_extra (msg,
596                             num_peers * sizeof (struct GNUNET_PeerIdentity),
597                             GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
598   msg->type = htonl (type);
599   msg->num_peers = htonl (num_peers);
600   if ( (2 == type) ||
601        (3 == type) )
602     msg->attacked_peer = *target_peer;
603   GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers * sizeof (struct GNUNET_PeerIdentity));
604
605   GNUNET_MQ_send (h->mq, ev);
606 }
607 #endif /* ENABLE_MALICIOUS */
608
609
610 /**
611  * Cancle an issued request.
612  *
613  * @param rh request handle of request to cancle
614  */
615 void
616 GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh)
617 {
618   struct GNUNET_RPS_Handle *h;
619   struct GNUNET_MQ_Envelope *ev;
620   struct GNUNET_RPS_CS_RequestCancelMessage*msg;
621
622   LOG (GNUNET_ERROR_TYPE_DEBUG,
623        "Cancelling request with id %" PRIu32 "\n",
624        rh->id);
625
626   h = rh->rps_handle;
627   GNUNET_assert (GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers,
628         rh->id));
629   GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, rh->id);
630   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL);
631   msg->id = htonl (rh->id);
632   GNUNET_MQ_send (rh->rps_handle->mq, ev);
633 }
634
635
636 /**
637  * Disconnect from the rps service
638  *
639  * @param h the handle to the rps service
640  */
641 void
642 GNUNET_RPS_disconnect (struct GNUNET_RPS_Handle *h)
643 {
644   GNUNET_MQ_destroy (h->mq);
645   if (0 < GNUNET_CONTAINER_multihashmap32_size (h->req_handlers))
646     LOG (GNUNET_ERROR_TYPE_WARNING,
647         "Still waiting for requests\n");
648   GNUNET_CONTAINER_multihashmap32_destroy (h->req_handlers);
649   GNUNET_free (h);
650 }
651
652
653 /* end of rps_api.c */