rps: add debug function to api to get view of service
[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   rps_handle->view_update_cb = view_update_cb;
270   rps_handle->view_update_cls = cls;
271
272   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REQUEST);
273   msg->num_updates = htonl (num_updates);
274   GNUNET_MQ_send (rps_handle->mq, ev);
275 }
276
277 /**
278  * This function is called, when the service updates the view.
279  * It verifies that @a msg is well-formed.
280  *
281  * @param cls the closure
282  * @param msg the message
283  * @return #GNUNET_OK if @a msg is well-formed
284  */
285 static int
286 check_view_update (void *cls,
287                    const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
288 {
289   uint16_t msize = ntohs (msg->header.size);
290   uint32_t num_peers = ntohl (msg->num_peers);
291
292   msize -= sizeof (struct GNUNET_RPS_CS_DEBUG_ViewReply);
293   if ( (msize / sizeof (struct GNUNET_PeerIdentity) != num_peers) ||
294        (msize % sizeof (struct GNUNET_PeerIdentity) != 0) )
295   {
296     GNUNET_break (0);
297     return GNUNET_SYSERR;
298   }
299   return GNUNET_OK;
300 }
301
302 /**
303  * This function is called, when the service updated its view.
304  * It calls the callback the caller provided
305  * and disconnects afterwards.
306  *
307  * @param msg the message
308  */
309 static void
310 handle_view_update (void *cls,
311                     const struct GNUNET_RPS_CS_DEBUG_ViewReply *msg)
312 {
313   struct GNUNET_RPS_Handle *h = cls;
314   struct GNUNET_PeerIdentity *peers;
315
316   /* Give the peers back */
317   LOG (GNUNET_ERROR_TYPE_DEBUG,
318        "New view of %" PRIu32 " peers:\n",
319        ntohl (msg->num_peers));
320
321   peers = (struct GNUNET_PeerIdentity *) &msg[1];
322   GNUNET_assert (NULL != h);
323   GNUNET_assert (NULL != h->view_update_cb);
324   h->view_update_cb (h->view_update_cls, ntohl (msg->num_peers), peers);
325 }
326
327
328
329 /**
330  * Reconnect to the service
331  */
332 static void
333 reconnect (struct GNUNET_RPS_Handle *h);
334
335
336 /**
337  * Error handler for mq.
338  *
339  * This function is called whan mq encounters an error.
340  * Until now mq doesn't provide useful error messages.
341  *
342  * @param cls the closure
343  * @param error error code without specyfied meaning
344  */
345 static void
346 mq_error_handler (void *cls,
347                   enum GNUNET_MQ_Error error)
348 {
349   struct GNUNET_RPS_Handle *h = cls;
350   //TODO LOG
351   LOG (GNUNET_ERROR_TYPE_WARNING, "Problem with message queue. error: %i\n\
352        1: READ,\n\
353        2: WRITE,\n\
354        4: TIMEOUT\n",
355        error);
356   reconnect (h);
357   /* Resend all pending request as the service destroyed its knowledge
358    * about them */
359   resend_requests (h);
360 }
361
362
363 /**
364  * Reconnect to the service
365  */
366 static void
367 reconnect (struct GNUNET_RPS_Handle *h)
368 {
369   struct GNUNET_MQ_MessageHandler mq_handlers[] = {
370     GNUNET_MQ_hd_var_size (reply,
371                            GNUNET_MESSAGE_TYPE_RPS_CS_REPLY,
372                            struct GNUNET_RPS_CS_ReplyMessage,
373                            h),
374     GNUNET_MQ_hd_var_size (view_update,
375                            GNUNET_MESSAGE_TYPE_RPS_CS_DEBUG_VIEW_REPLY,
376                            struct GNUNET_RPS_CS_DEBUG_ViewReply,
377                            h),
378     GNUNET_MQ_handler_end ()
379   };
380
381   if (NULL != h->mq)
382     GNUNET_MQ_destroy (h->mq);
383   h->mq = GNUNET_CLIENT_connect (h->cfg,
384                                  "rps",
385                                  mq_handlers,
386                                  &mq_error_handler,
387                                  h);
388 }
389
390
391 /**
392  * Connect to the rps service
393  *
394  * @param cfg configuration to use
395  * @return a handle to the service
396  */
397 struct GNUNET_RPS_Handle *
398 GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
399 {
400   struct GNUNET_RPS_Handle *h;
401
402   h = GNUNET_new (struct GNUNET_RPS_Handle);
403   h->current_request_id = 0;
404   h->cfg = cfg;
405   reconnect (h);
406   if (NULL == h->mq)
407   {
408     GNUNET_free (h);
409     return NULL;
410   }
411   h->req_handlers = GNUNET_CONTAINER_multihashmap32_create (4);
412   return h;
413 }
414
415
416 /**
417  * Request n random peers.
418  *
419  * @param rps_handle handle to the rps service
420  * @param num_req_peers number of peers we want to receive
421  * @param ready_cb the callback called when the peers are available
422  * @param cls closure given to the callback
423  * @return a handle to cancel this request
424  */
425 struct GNUNET_RPS_Request_Handle *
426 GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *rps_handle,
427                           uint32_t num_req_peers,
428                           GNUNET_RPS_NotifyReadyCB ready_cb,
429                           void *cls)
430 {
431   struct GNUNET_RPS_Request_Handle *rh;
432
433   rh = GNUNET_new (struct GNUNET_RPS_Request_Handle);
434   rh->rps_handle = rps_handle;
435   rh->id = rps_handle->current_request_id++;
436   rh->num_peers = num_req_peers;
437   rh->ready_cb = ready_cb;
438   rh->ready_cb_cls = cls;
439
440   LOG (GNUNET_ERROR_TYPE_DEBUG,
441        "Requesting %" PRIu32 " peers with id %" PRIu32 "\n",
442        num_req_peers,
443        rh->id);
444
445   GNUNET_CONTAINER_multihashmap32_put (rps_handle->req_handlers, rh->id, rh,
446       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
447
448   send_request (rps_handle, rh->id, num_req_peers);
449   return rh;
450 }
451
452
453 /**
454  * Seed rps service with peerIDs.
455  *
456  * @param h handle to the rps service
457  * @param n number of peers to seed
458  * @param ids the ids of the peers seeded
459  */
460 void
461 GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h,
462                      uint32_t n,
463                      const struct GNUNET_PeerIdentity *ids)
464 {
465   size_t size_needed;
466   uint32_t num_peers_max;
467   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
468   struct GNUNET_MQ_Envelope *ev;
469   struct GNUNET_RPS_CS_SeedMessage *msg;
470
471   unsigned int i;
472
473   LOG (GNUNET_ERROR_TYPE_DEBUG,
474        "Client wants to seed %" PRIu32 " peers:\n",
475        n);
476   for (i = 0 ; i < n ; i++)
477     LOG (GNUNET_ERROR_TYPE_DEBUG,
478          "%u. peer: %s\n",
479          i,
480          GNUNET_i2s (&ids[i]));
481
482   /* The actual size the message occupies */
483   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
484     n * sizeof (struct GNUNET_PeerIdentity);
485   /* The number of peers that fits in one message together with
486    * the respective header */
487   num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
488       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
489     sizeof (struct GNUNET_PeerIdentity);
490   tmp_peer_pointer = ids;
491
492   while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
493   {
494     ev = GNUNET_MQ_msg_extra (msg, num_peers_max * sizeof (struct GNUNET_PeerIdentity),
495         GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
496     msg->num_peers = htonl (num_peers_max);
497     GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers_max * sizeof (struct GNUNET_PeerIdentity));
498     GNUNET_MQ_send (h->mq, ev);
499
500     n -= num_peers_max;
501     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
502                   n * sizeof (struct GNUNET_PeerIdentity);
503     /* Set pointer to beginning of next block of num_peers_max peers */
504     tmp_peer_pointer = &ids[num_peers_max];
505   }
506
507   ev = GNUNET_MQ_msg_extra (msg, n * sizeof (struct GNUNET_PeerIdentity),
508                             GNUNET_MESSAGE_TYPE_RPS_CS_SEED);
509   msg->num_peers = htonl (n);
510   GNUNET_memcpy (&msg[1], tmp_peer_pointer, n * sizeof (struct GNUNET_PeerIdentity));
511
512   GNUNET_MQ_send (h->mq, ev);
513 }
514
515
516 #ifdef ENABLE_MALICIOUS
517 /**
518  * Turn RPS service to act malicious.
519  *
520  * @param h handle to the rps service
521  * @param type which type of malicious peer to turn to.
522  *             0 Don't act malicious at all
523  *             1 Try to maximise representation
524  *             2 Try to partition the network
525  *               (isolate one peer from the rest)
526  * @param n number of @a ids
527  * @param ids the ids of the malicious peers
528  *            if @type is 2 the last id is the id of the
529  *            peer to be isolated from the rest
530  */
531 void
532 GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h,
533                           uint32_t type,
534                           uint32_t num_peers,
535                           const struct GNUNET_PeerIdentity *peer_ids,
536                           const struct GNUNET_PeerIdentity *target_peer)
537 {
538   size_t size_needed;
539   uint32_t num_peers_max;
540   const struct GNUNET_PeerIdentity *tmp_peer_pointer;
541   struct GNUNET_MQ_Envelope *ev;
542   struct GNUNET_RPS_CS_ActMaliciousMessage *msg;
543
544   unsigned int i;
545
546   LOG (GNUNET_ERROR_TYPE_DEBUG,
547        "Client turns malicious (type %" PRIu32 ") with %" PRIu32 " other peers:\n",
548        type,
549        num_peers);
550   for (i = 0 ; i < num_peers ; i++)
551     LOG (GNUNET_ERROR_TYPE_DEBUG,
552          "%u. peer: %s\n",
553          i,
554          GNUNET_i2s (&peer_ids[i]));
555
556   /* The actual size the message would occupy */
557   size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
558     num_peers * sizeof (struct GNUNET_PeerIdentity);
559   /* The number of peers that fit in one message together with
560    * the respective header */
561   num_peers_max = (GNUNET_MAX_MESSAGE_SIZE -
562       sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
563     sizeof (struct GNUNET_PeerIdentity);
564   tmp_peer_pointer = peer_ids;
565
566   while (GNUNET_MAX_MESSAGE_SIZE < size_needed)
567   {
568     LOG (GNUNET_ERROR_TYPE_DEBUG,
569          "Too many peers to send at once, sending %" PRIu32 " (all we can so far)\n",
570          num_peers_max);
571     ev = GNUNET_MQ_msg_extra (msg,
572                               num_peers_max * sizeof (struct GNUNET_PeerIdentity),
573                               GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
574     msg->type = htonl (type);
575     msg->num_peers = htonl (num_peers_max);
576     if ( (2 == type) ||
577          (3 == type) )
578       msg->attacked_peer = peer_ids[num_peers];
579     GNUNET_memcpy (&msg[1],
580             tmp_peer_pointer,
581             num_peers_max * sizeof (struct GNUNET_PeerIdentity));
582
583     GNUNET_MQ_send (h->mq, ev);
584
585     num_peers -= num_peers_max;
586     size_needed = sizeof (struct GNUNET_RPS_CS_SeedMessage) +
587                   num_peers * sizeof (struct GNUNET_PeerIdentity);
588     /* Set pointer to beginning of next block of num_peers_max peers */
589     tmp_peer_pointer = &peer_ids[num_peers_max];
590   }
591
592   ev = GNUNET_MQ_msg_extra (msg,
593                             num_peers * sizeof (struct GNUNET_PeerIdentity),
594                             GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS);
595   msg->type = htonl (type);
596   msg->num_peers = htonl (num_peers);
597   if ( (2 == type) ||
598        (3 == type) )
599     msg->attacked_peer = *target_peer;
600   GNUNET_memcpy (&msg[1], tmp_peer_pointer, num_peers * sizeof (struct GNUNET_PeerIdentity));
601
602   GNUNET_MQ_send (h->mq, ev);
603 }
604 #endif /* ENABLE_MALICIOUS */
605
606
607 /**
608  * Cancle an issued request.
609  *
610  * @param rh request handle of request to cancle
611  */
612 void
613 GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh)
614 {
615   struct GNUNET_RPS_Handle *h;
616   struct GNUNET_MQ_Envelope *ev;
617   struct GNUNET_RPS_CS_RequestCancelMessage*msg;
618
619   LOG (GNUNET_ERROR_TYPE_DEBUG,
620        "Cancelling request with id %" PRIu32 "\n",
621        rh->id);
622
623   h = rh->rps_handle;
624   GNUNET_assert (GNUNET_CONTAINER_multihashmap32_contains (h->req_handlers,
625         rh->id));
626   GNUNET_CONTAINER_multihashmap32_remove_all (h->req_handlers, rh->id);
627   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST_CANCEL);
628   msg->id = htonl (rh->id);
629   GNUNET_MQ_send (rh->rps_handle->mq, ev);
630 }
631
632
633 /**
634  * Disconnect from the rps service
635  *
636  * @param h the handle to the rps service
637  */
638 void
639 GNUNET_RPS_disconnect (struct GNUNET_RPS_Handle *h)
640 {
641   GNUNET_MQ_destroy (h->mq);
642   if (0 < GNUNET_CONTAINER_multihashmap32_size (h->req_handlers))
643     LOG (GNUNET_ERROR_TYPE_WARNING,
644         "Still waiting for requests\n");
645   GNUNET_CONTAINER_multihashmap32_destroy (h->req_handlers);
646   GNUNET_free (h);
647 }
648
649
650 /* end of rps_api.c */