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