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