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