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