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