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