aboutsummaryrefslogtreecommitdiff
path: root/src/scalarproduct/scalarproduct_api.c
blob: dcacd85c98152c7ee1f11d21977b4e6738915610 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
     This file is part of GNUnet.
     (C) 2013 Christian Grothoff (and other contributing authors)

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
 */

/**
 * @file scalarproduct/scalarproduct_api.c
 * @brief API for the scalarproduct
 * @author Christian Fuchs
 * @author Gaurav Kukreja
 *
 */
#include "platform.h"
#include "gnunet_util_lib.h"
#include "gnunet_statistics_service.h"
#include "gnunet_scalarproduct_service.h"
#include "gnunet_protocols.h"
#include "scalarproduct.h"

#define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct-api",__VA_ARGS__)

/**************************************************************
 ***  Datatype Declarations                          **********
 **************************************************************/

/**
 * the abstraction function for our internal callback
 */
typedef void (*GNUNET_SCALARPRODUCT_ResponseMessageHandler) (void *cls,
                                                             const struct GNUNET_MessageHeader *msg,
                                                             enum GNUNET_SCALARPRODUCT_ResponseStatus status);

/**
 * Entry in the request queue per client
 */
struct GNUNET_SCALARPRODUCT_ComputationHandle
{
  /**
   * This is a linked list.
   */
  struct GNUNET_SCALARPRODUCT_ComputationHandle *next;

  /**
   * This is a linked list.
   */
  struct GNUNET_SCALARPRODUCT_ComputationHandle *prev;

  /**
   * Our configuration.
   */
  const struct GNUNET_CONFIGURATION_Handle *cfg;

  /**
   * Current connection to the scalarproduct service.
   */
  struct GNUNET_CLIENT_Connection *client;

  /**
   * Handle for statistics.
   */
  struct GNUNET_STATISTICS_Handle *stats;

  /**
   * The shared session key identifying this computation
   */
  struct GNUNET_HashCode key;

  /**
   * Current transmit handle.
   */
  struct GNUNET_CLIENT_TransmitHandle *th;

  /**
   * Size of the message
   */
  uint16_t message_size;

  /**
   * Message to be sent to the scalarproduct service
   */
  struct GNUNET_SCALARPRODUCT_client_request * msg;

  /**
   * The msg handler callback
   */
  union
  {
  /**
   * Function to call after transmission of the request.
   */
  GNUNET_SCALARPRODUCT_ContinuationWithStatus cont_status;

  /**
   * Function to call after transmission of the request.
   */
  GNUNET_SCALARPRODUCT_DatumProcessor cont_datum;
  };

  /**
   * Closure for 'cont'.
   */
  void *cont_cls;

  /**
   * Response Processor for response from the service. This function calls the
   * continuation function provided by the client.
   */
  GNUNET_SCALARPRODUCT_ResponseMessageHandler response_proc;
};

/**************************************************************
 ***  Global Variables                               **********
 **************************************************************/
/**
 * Head of the active sessions queue
 */
static struct GNUNET_SCALARPRODUCT_ComputationHandle *head;
/**
 * Tail of the active sessions queue
 */
static struct GNUNET_SCALARPRODUCT_ComputationHandle *tail;

/**************************************************************
 ***  Function Declarations                          **********
 **************************************************************/

void
GNUNET_SCALARPRODUCT_cancel (struct GNUNET_SCALARPRODUCT_ComputationHandle * h);

/**************************************************************
 ***  Static Function Declarations                   **********
 **************************************************************/


/**
 * Handles the STATUS received from the service for a response, does not contain a payload
 *
 * @param cls our Handle
 * @param msg Pointer to the response received
 * @param status the condition the request was terminated with (eg: disconnect)
 */
static void
process_status_message (void *cls,
                        const struct GNUNET_MessageHeader *msg,
                        enum GNUNET_SCALARPRODUCT_ResponseStatus status)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *qe = cls;

  qe->cont_status (qe->cont_cls, status);
}


/**
 * Handles the RESULT received from the service for a request, should contain a result MPI value
 *
 * @param cls our Handle
 * @param msg Pointer to the response received
 * @param status the condition the request was terminated with (eg: disconnect)
 */
static void
process_result_message (void *cls,
                        const struct GNUNET_MessageHeader *msg,
                        enum GNUNET_SCALARPRODUCT_ResponseStatus status)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *qe = cls;
  const struct GNUNET_SCALARPRODUCT_client_response *message =
          (const struct GNUNET_SCALARPRODUCT_client_response *) msg;
  gcry_mpi_t result = NULL;
  gcry_error_t rc;

  if (GNUNET_SCALARPRODUCT_Status_Success == status)
    {
      size_t product_len = ntohl (message->product_length);
      result = gcry_mpi_new (0);

      if (0 < product_len)
        {
          gcry_mpi_t num;
          size_t read = 0;

          if (0 != (rc = gcry_mpi_scan (&num, GCRYMPI_FMT_STD, &message[1], product_len, &read)))
            {
              LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
              gcry_mpi_release (result);
              result = NULL;
              status = GNUNET_SCALARPRODUCT_Status_InvalidResponse;
            }
          else
            {
              if (0 < message->range)
                gcry_mpi_add (result, result, num);
              else if (0 > message->range)
                gcry_mpi_sub (result, result, num);
              gcry_mpi_release (num);
            }
        }
    }
  qe->cont_datum (qe->cont_cls, status, result);
}


/**
 * Called when a response is received from the service. After basic check, the
 * handler in qe->response_proc is called. This functions handles the response
 * to the client which used the API.
 *
 * @param cls Pointer to the Master Context
 * @param msg Pointer to the data received in response
 */
static void
receive_cb (void *cls, const struct GNUNET_MessageHeader *msg)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *qe = cls;
  const struct GNUNET_SCALARPRODUCT_client_response *message =
          (const struct GNUNET_SCALARPRODUCT_client_response *) msg;
  enum GNUNET_SCALARPRODUCT_ResponseStatus status = GNUNET_SCALARPRODUCT_Status_InvalidResponse;

  if (NULL == msg)
    {
      LOG (GNUNET_ERROR_TYPE_WARNING, "Disconnected by Service.\n");
      status = GNUNET_SCALARPRODUCT_Status_ServiceDisconnected;
    }
  else if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT != ntohs (msg->type))
    {
      LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid message type received\n");
    }
  else if (0 < ntohl (message->product_length) || (0 == message->range))
    {
      // response for the responder client, successful
      GNUNET_STATISTICS_update (qe->stats,
                                gettext_noop ("# SUC responder result messages received"), 1,
                                GNUNET_NO);

      status = GNUNET_SCALARPRODUCT_Status_Success;
    }

  if (qe->cont_datum != NULL)
    qe->response_proc (qe, msg, status);

  GNUNET_CONTAINER_DLL_remove (head, tail, qe);
  GNUNET_free (qe);
}


/**
 * Transmits the request to the VectorProduct Service
 *
 * @param cls Closure
 * @param size Size of the buffer
 * @param buf Pointer to the buffer
 *
 * @return Size of the message sent
 */
static size_t
transmit_request (void *cls, size_t size,
                  void *buf)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *qe = cls;

  if (NULL == buf)
    {
      LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to transmit request to SCALARPRODUCT.\n");
      GNUNET_STATISTICS_update (qe->stats,
                                gettext_noop ("# transmission request failures"),
                                1, GNUNET_NO);

      // notify caller about the error, done here.
      if (qe->cont_datum != NULL)
        qe->response_proc (qe, NULL, GNUNET_SCALARPRODUCT_Status_Failure);

      GNUNET_SCALARPRODUCT_cancel (cls);
      return 0;
    }
  memcpy (buf, qe->msg, size);

  GNUNET_free (qe->msg);
  qe->msg = NULL;
  qe->th = NULL;

  GNUNET_CLIENT_receive (qe->client, &receive_cb, qe,
                         GNUNET_TIME_UNIT_FOREVER_REL);

#if INSANE_STATISTICS
  GNUNET_STATISTICS_update (qe->stats,
                            gettext_noop ("# bytes sent to scalarproduct"), 1,
                            GNUNET_NO);
#endif
  return size;
}


/**************************************************************
 ***  API                                            **********
 **************************************************************/


/**
 * Used by Bob's client to cooperate with Alice,
 *
 * @param cfg the gnunet configuration handle
 * @param key Session key unique to the requesting client
 * @param elements Array of elements of the vector
 * @param element_count Number of elements in the vector
 * @param cont Callback function
 * @param cont_cls Closure for the callback function
 * 
 * @return a new handle for this computation
 */
struct GNUNET_SCALARPRODUCT_ComputationHandle *
GNUNET_SCALARPRODUCT_response (const struct GNUNET_CONFIGURATION_Handle * cfg,
                               const struct GNUNET_HashCode * key,
                               const int32_t * elements,
                               uint32_t element_count,
                               GNUNET_SCALARPRODUCT_ContinuationWithStatus cont,
                               void * cont_cls)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *h;
  struct GNUNET_SCALARPRODUCT_client_request *msg;
  int32_t * vector;
  uint16_t size;
  uint64_t i;

  GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_client_request)
                 + element_count * sizeof (int32_t));
  h = GNUNET_new (struct GNUNET_SCALARPRODUCT_ComputationHandle);
  h->client = GNUNET_CLIENT_connect ("scalarproduct", cfg);
  if (!h->client)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to connect to the scalarproduct service\n"));
      GNUNET_free (h);
      return NULL;
    }
  h->stats = GNUNET_STATISTICS_create ("scalarproduct-api", cfg);
  if (!h->stats)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to send a message to the statistics service\n"));
      GNUNET_CLIENT_disconnect (h->client);
      GNUNET_free (h);
      return NULL;
    }

  size = sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t);

  h->cont_status = cont;
  h->cont_cls = cont_cls;
  h->response_proc = &process_status_message;
  h->cfg = cfg;
  memcpy (&h->key, key, sizeof (struct GNUNET_HashCode));

  msg = (struct GNUNET_SCALARPRODUCT_client_request*) GNUNET_malloc (size);
  h->msg = msg;
  msg->header.size = htons (size);
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB);
  msg->element_count = htonl (element_count);

  vector = (int32_t*) & msg[1];
  // copy each element over to the message
  for (i = 0; i < element_count; i++)
    vector[i] = htonl (elements[i]);

  memcpy (&msg->key, key, sizeof (struct GNUNET_HashCode));

  h->th = GNUNET_CLIENT_notify_transmit_ready (h->client, size,
                                               GNUNET_TIME_UNIT_FOREVER_REL,
                                               GNUNET_YES, // retry is OK in the initial stage
                                               &transmit_request, h);
  if (!h->th)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to send a message to the scalarproduct service\n"));
      GNUNET_STATISTICS_destroy (h->stats, GNUNET_YES);
      GNUNET_CLIENT_disconnect (h->client);
      GNUNET_free (h->msg);
      GNUNET_free (h);
      return NULL;
    }
  GNUNET_CONTAINER_DLL_insert (head, tail, h);
  return h;
}


/**
 * Request by Alice's client for computing a scalar product
 *
 * @param cfg the gnunet configuration handle
 * @param key Session key should be unique to the requesting client
 * @param peer PeerID of the other peer
 * @param elements Array of elements of the vector
 * @param element_count Number of elements in the vector
 * @param mask Array of the mask
 * @param mask_bytes number of bytes in the mask
 * @param cont Callback function
 * @param cont_cls Closure for the callback function
 * 
 * @return a new handle for this computation
 */
struct GNUNET_SCALARPRODUCT_ComputationHandle *
GNUNET_SCALARPRODUCT_request (const struct GNUNET_CONFIGURATION_Handle * cfg,
                              const struct GNUNET_HashCode * key,
                              const struct GNUNET_PeerIdentity *peer,
                              const int32_t * elements,
                              uint32_t element_count,
                              const unsigned char * mask,
                              uint32_t mask_bytes,
                              GNUNET_SCALARPRODUCT_DatumProcessor cont,
                              void * cont_cls)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle *h;
  struct GNUNET_SCALARPRODUCT_client_request *msg;
  int32_t * vector;
  uint16_t size;
  uint64_t i;

  GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_client_request)
                 +element_count * sizeof (int32_t)
                 + mask_bytes);

  h = GNUNET_new (struct GNUNET_SCALARPRODUCT_ComputationHandle);
  h->client = GNUNET_CLIENT_connect ("scalarproduct", cfg);
  if (!h->client)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to connect to the scalarproduct service\n"));
      GNUNET_free (h);
      return NULL;
    }
  h->stats = GNUNET_STATISTICS_create ("scalarproduct-api", cfg);
  if (!h->stats)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to send a message to the statistics service\n"));
      GNUNET_CLIENT_disconnect (h->client);
      GNUNET_free (h);
      return NULL;
    }

  size = sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_bytes;

  h->cont_datum = cont;
  h->cont_cls = cont_cls;
  h->response_proc = &process_result_message;
  h->cfg = cfg;
  memcpy (&h->key, key, sizeof (struct GNUNET_HashCode));

  msg = (struct GNUNET_SCALARPRODUCT_client_request*) GNUNET_malloc (size);
  h->msg = msg;
  msg->header.size = htons (size);
  msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE);
  msg->element_count = htonl (element_count);
  msg->mask_length = htonl (mask_bytes);

  vector = (int32_t*) & msg[1];
  // copy each element over to the message
  for (i = 0; i < element_count; i++)
    vector[i] = htonl (elements[i]);

  memcpy (&msg->peer, peer, sizeof (struct GNUNET_PeerIdentity));
  memcpy (&msg->key, key, sizeof (struct GNUNET_HashCode));
  memcpy (&vector[element_count], mask, mask_bytes);

  h->th = GNUNET_CLIENT_notify_transmit_ready (h->client, size,
                                               GNUNET_TIME_UNIT_FOREVER_REL,
                                               GNUNET_YES, // retry is OK in the initial stage
                                               &transmit_request, h);
  if (!h->th)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR,
           _ ("Failed to send a message to the scalarproduct service\n"));
      GNUNET_STATISTICS_destroy (h->stats, GNUNET_YES);
      GNUNET_CLIENT_disconnect (h->client);
      GNUNET_free (h->msg);
      GNUNET_free (h);
      return NULL;
    }
  GNUNET_CONTAINER_DLL_insert (head, tail, h);
  return h;
}


/**
 * Cancel an ongoing computation or revoke our collaboration offer.
 * Closes the connection to the service
 *
 * @param h computation handle to terminate
 */
void
GNUNET_SCALARPRODUCT_cancel (struct GNUNET_SCALARPRODUCT_ComputationHandle * h)
{
  struct GNUNET_SCALARPRODUCT_ComputationHandle * qe;

  for (qe = head; head != NULL; qe = head)
    {
      if (qe == h)
        {
          GNUNET_CONTAINER_DLL_remove (head, tail, qe);
          if (NULL != qe->th)
            GNUNET_CLIENT_notify_transmit_ready_cancel (qe->th);
          GNUNET_CLIENT_disconnect (qe->client);
          GNUNET_STATISTICS_destroy (qe->stats, GNUNET_YES);
          GNUNET_free_non_null (qe->msg);
          GNUNET_free (qe);
          break;
        }
    }
}
/**
 * Cancel ALL ongoing computation or revoke our collaboration offer.
 * Closes ALL connections to the service
 */
void
GNUNET_SCALARPRODUCT_disconnect ()
{
    struct GNUNET_SCALARPRODUCT_ComputationHandle * qe;

    LOG (GNUNET_ERROR_TYPE_INFO, "Disconnecting from VectorProduct\n");
    for (qe = head; head != NULL; qe = head)
    {
        GNUNET_CONTAINER_DLL_remove (head, tail, qe);
        if (NULL != qe->th)
            GNUNET_CLIENT_notify_transmit_ready_cancel (qe->th);
        GNUNET_CLIENT_disconnect (qe->client);
        GNUNET_STATISTICS_destroy (qe->stats, GNUNET_YES);
        GNUNET_free_non_null (qe->msg);
        GNUNET_free (qe);
    }
}

/* end of scalarproduct_api.c */