2 This file is part of GNUnet.
3 (C) 2013 Christian Grothoff (and other contributing authors)
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.
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.
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., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file scalarproduct/gnunet-service-scalarproduct.c
23 * @brief scalarproduct service implementation
24 * @author Christian M. Fuchs
28 #include "gnunet_util_lib.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_mesh_service.h"
31 #include "gnunet_applications.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_scalarproduct_service.h"
34 #include "scalarproduct.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
38 ///////////////////////////////////////////////////////////////////////////////
39 // Service Structure Definitions
40 ///////////////////////////////////////////////////////////////////////////////
44 * state a session can be in
48 CLIENT_REQUEST_RECEIVED,
49 WAITING_FOR_BOBS_CONNECT,
50 CLIENT_RESPONSE_RECEIVED,
51 WAITING_FOR_SERVICE_REQUEST,
52 WAITING_FOR_MULTIPART_TRANSMISSION,
53 WAITING_FOR_SERVICE_RESPONSE,
54 SERVICE_REQUEST_RECEIVED,
55 SERVICE_RESPONSE_RECEIVED,
61 * role a peer in a session can assume
71 * A scalarproduct session which tracks:
73 * a request form the client to our final response.
75 * a request from a service to us(service).
80 * the role this peer has
85 * session information is kept in a DLL
87 struct ServiceSession *next;
90 * session information is kept in a DLL
92 struct ServiceSession *prev;
95 * (hopefully) unique transaction ID
97 struct GNUNET_HashCode key;
100 * state of the session
102 enum SessionState state;
105 * Alice or Bob's peerID
107 struct GNUNET_PeerIdentity peer;
110 * the client this request is related to
112 struct GNUNET_SERVER_Client * client;
115 * The message to send
117 struct GNUNET_MessageHeader * msg;
120 * how many elements we were supplied with from the client
125 * how many elements actually are used after applying the mask
130 * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
132 uint32_t transferred;
135 * index of the last transferred element for multipart messages
137 uint32_t last_processed;
140 * how many bytes the mask is long.
141 * just for convenience so we don't have to re-re-re calculate it each time
143 uint32_t mask_length;
146 * all the vector elements we received
151 * mask of which elements to check
153 unsigned char * mask;
156 * Public key of the remote service, only used by bob
158 gcry_sexp_t remote_pubkey;
161 * E(ai)(Bob) or ai(Alice) after applying the mask
166 * Bob's permutation p of R
171 * Bob's permutation q of R
173 gcry_mpi_t * r_prime;
186 * Bobs matching response session from the client
188 struct ServiceSession * response;
191 * The computed scalar
196 * My transmit handle for the current message to a alice/bob
198 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
201 * My transmit handle for the current message to the client
203 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
206 * channel-handle associated with our mesh handle
208 struct GNUNET_MESH_Channel * channel;
211 * Handle to a task that sends a msg to the our client
213 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
216 * Handle to a task that sends a msg to the our peer
218 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
221 ///////////////////////////////////////////////////////////////////////////////
222 // Forward Delcarations
223 ///////////////////////////////////////////////////////////////////////////////
226 * Send a multi part chunk of a service request from alice to bob.
227 * This element only contains a part of the elements-vector (session->a[]),
228 * mask and public key set have to be contained within the first message
230 * This allows a ~32kbit key length while using 32000 elements or 62000 elements per request.
232 * @param cls the associated service session
235 prepare_service_request_multipart (void *cls);
238 * Send a multi part chunk of a service response from bob to alice.
239 * This element only contains the two permutations of R, R'.
241 * @param cls the associated service session
244 prepare_service_response_multipart (void *cls);
247 ///////////////////////////////////////////////////////////////////////////////
249 ///////////////////////////////////////////////////////////////////////////////
253 * Handle to the core service (NULL until we've connected to it).
255 static struct GNUNET_MESH_Handle *my_mesh;
258 * The identity of this host.
260 static struct GNUNET_PeerIdentity me;
263 * Service's own public key represented as string
265 static unsigned char * my_pubkey_external;
268 * Service's own public key represented as string
270 static uint32_t my_pubkey_external_length = 0;
275 static gcry_mpi_t my_n;
278 * Service's own n^2 (kept for performance)
280 static gcry_mpi_t my_nsquare;
283 * Service's own public exponent
285 static gcry_mpi_t my_g;
288 * Service's own private multiplier
290 static gcry_mpi_t my_mu;
293 * Service's own private exponent
295 static gcry_mpi_t my_lambda;
298 * Service's offset for values that could possibly be negative but are plaintext for encryption.
300 static gcry_mpi_t my_offset;
303 * Head of our double linked list for client-requests sent to us.
304 * for all of these elements we calculate a scalar product with a remote peer
305 * split between service->service and client->service for simplicity
307 static struct ServiceSession * from_client_head;
309 * Tail of our double linked list for client-requests sent to us.
310 * for all of these elements we calculate a scalar product with a remote peer
311 * split between service->service and client->service for simplicity
313 static struct ServiceSession * from_client_tail;
316 * Head of our double linked list for service-requests sent to us.
317 * for all of these elements we help the requesting service in calculating a scalar product
318 * split between service->service and client->service for simplicity
320 static struct ServiceSession * from_service_head;
323 * Tail of our double linked list for service-requests sent to us.
324 * for all of these elements we help the requesting service in calculating a scalar product
325 * split between service->service and client->service for simplicity
327 static struct ServiceSession * from_service_tail;
330 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
332 static int do_shutdown;
334 ///////////////////////////////////////////////////////////////////////////////
336 ///////////////////////////////////////////////////////////////////////////////
340 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
345 gcry_sexp_t gen_params;
347 gcry_sexp_t tmp_sexp;
356 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
357 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
358 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
361 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
362 gcry_sexp_release (gen_params);
364 // get n and d of our publickey as MPI
365 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
366 GNUNET_assert (tmp_sexp);
367 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
368 gcry_sexp_release (tmp_sexp);
369 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
370 GNUNET_assert (tmp_sexp);
371 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
372 gcry_sexp_release (tmp_sexp);
373 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
374 GNUNET_assert (tmp_sexp);
375 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
376 gcry_sexp_release (key);
378 tmp1 = gcry_mpi_new (0);
379 tmp2 = gcry_mpi_new (0);
380 gcd = gcry_mpi_new (0);
381 my_g = gcry_mpi_new (0);
382 my_mu = gcry_mpi_new (0);
383 my_nsquare = gcry_mpi_new (0);
384 my_lambda = gcry_mpi_new (0);
387 // lambda = frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
388 gcry_mpi_sub_ui (tmp1, p, 1);
389 gcry_mpi_sub_ui (tmp2, q, 1);
390 gcry_mpi_gcd (gcd, tmp1, tmp2);
391 gcry_mpi_set (my_lambda, tmp1);
392 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
393 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
396 gcry_mpi_mul (my_nsquare, my_n, my_n);
400 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
401 // g must be smaller than n^2
402 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
405 // g must have gcd == 1 with n^2
406 gcry_mpi_gcd (gcd, my_g, my_nsquare);
408 while (gcry_mpi_cmp_ui (gcd, 1));
410 // is this a valid g?
411 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
412 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
413 gcry_mpi_sub_ui (tmp1, tmp1, 1);
414 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
415 gcry_mpi_gcd (gcd, tmp1, my_n);
417 while (gcry_mpi_cmp_ui (gcd, 1));
419 // calculate our mu based on g and n.
420 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
421 gcry_mpi_invm (my_mu, tmp1, my_n);
423 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
424 "(public-key (paillier (n %M)(g %M)))",
427 // get the length of this sexpression
428 my_pubkey_external_length = gcry_sexp_sprint (key,
433 GNUNET_assert (my_pubkey_external_length > 0);
434 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
436 // convert the sexpression to canonical format
437 gcry_sexp_sprint (key,
440 my_pubkey_external_length);
442 gcry_sexp_release (key);
444 // offset has to be sufficiently small to allow computation of:
445 // m1+m2 mod n == (S + a) + (S + b) mod n,
446 // if we have more complex operations, this factor needs to be lowered
447 my_offset = gcry_mpi_new (KEYBITS / 3);
448 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
455 * If target != size, move target bytes to the
456 * end of the size-sized buffer and zero out the
457 * first target-size bytes.
459 * @param buf original buffer
460 * @param size number of bytes in the buffer
461 * @param target target size of the buffer
464 adjust (unsigned char *buf, size_t size, size_t target)
467 memmove (&buf[target - size], buf, size);
468 memset (buf, 0, target - size);
474 * Encrypts an element using the paillier crypto system
476 * @param c ciphertext (output)
478 * @param g the public base
479 * @param n the module from which which r is chosen (Z*_n)
480 * @param n_square the module for encryption, for performance reasons.
483 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
487 GNUNET_assert (tmp = gcry_mpi_new (0));
489 while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
490 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
491 // r must be 1 < r < n
494 gcry_mpi_powm (c, g, m, n_square);
495 gcry_mpi_powm (tmp, tmp, n, n_square);
496 gcry_mpi_mulm (c, tmp, c, n_square);
498 gcry_mpi_release (tmp);
503 * decrypts an element using the paillier crypto system
505 * @param m plaintext (output)
506 * @param c the ciphertext
507 * @param mu the modifier to correct encryption
508 * @param lambda the private exponent
509 * @param n the outer module for decryption
510 * @param n_square the inner module for decryption
513 decrypt_element (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda, gcry_mpi_t n, gcry_mpi_t n_square)
515 gcry_mpi_powm (m, c, lambda, n_square);
516 gcry_mpi_sub_ui (m, m, 1);
517 gcry_mpi_div (m, NULL, m, n, 0);
518 gcry_mpi_mulm (m, m, mu, n);
523 * computes the square sum over a vector of a given length.
525 * @param vector the vector to encrypt
526 * @param length the length of the vector
527 * @return an MPI value containing the calculated sum, never NULL
530 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
536 GNUNET_assert (sum = gcry_mpi_new (0));
537 GNUNET_assert (elem = gcry_mpi_new (0));
539 // calculare E(sum (ai ^ 2), publickey)
540 for (i = 0; i < length; i++) {
541 gcry_mpi_mul (elem, vector[i], vector[i]);
542 gcry_mpi_add (sum, sum, elem);
544 gcry_mpi_release (elem);
551 * Primitive callback for copying over a message, as they
552 * usually are too complex to be handled in the callback itself.
553 * clears a session-callback, if a session was handed over and the transmit handle was stored
555 * @param cls the message object
556 * @param size the size of the buffer we got
557 * @param buf the buffer to copy the message to
558 * @return 0 if we couldn't copy, else the size copied over
561 do_send_message (void *cls, size_t size, void *buf)
563 struct ServiceSession * session = cls;
568 if (ntohs (session->msg->size) != size) {
573 type = ntohs (session->msg->type);
574 memcpy (buf, session->msg, size);
575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
576 "Sent a message of type %hu.\n",
578 GNUNET_free (session->msg);
583 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
584 session->state = FINALIZED;
585 session->client_transmit_handle = NULL;
588 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
589 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
590 session->service_transmit_handle = NULL;
591 if (session->state == WAITING_FOR_MULTIPART_TRANSMISSION)
592 prepare_service_request_multipart (session);
595 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
596 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
597 session->service_transmit_handle = NULL;
598 if (session->state == WAITING_FOR_MULTIPART_TRANSMISSION)
599 prepare_service_response_multipart (session);
611 * initializes a new vector with fresh MPI values (=0) of a given length
613 * @param length of the vector to create
614 * @return the initialized vector, never NULL
617 initialize_mpi_vector (uint32_t length)
620 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
622 for (i = 0; i < length; i++)
623 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
629 * permutes an MPI vector according to the given permutation vector
631 * @param vector the vector to permuted
632 * @param perm the permutation to use
633 * @param length the length of the vectors
634 * @return the permuted vector (same as input), never NULL
637 permute_vector (gcry_mpi_t * vector,
641 gcry_mpi_t tmp[length];
644 GNUNET_assert (length > 0);
647 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
649 // permute vector according to given
650 for (i = 0; i < length; i++)
651 vector[i] = tmp[perm[i]];
658 * Finds a not terminated client/service session in the
659 * given DLL based on session key, element count and state.
661 * @param tail - the tail of the DLL
662 * @param key - the key we want to search for
663 * @param element_count - the total element count of the dataset (session->total)
664 * @param state - a pointer to the state the session should be in, NULL to ignore
665 * @param peerid - a pointer to the peer ID of the associated peer, NULL to ignore
666 * @return a pointer to a matching session, or NULL
668 static struct ServiceSession *
669 find_matching_session (struct ServiceSession * tail,
670 const struct GNUNET_HashCode * key,
671 uint32_t element_count,
672 enum SessionState * state,
673 const struct GNUNET_PeerIdentity * peerid)
675 struct ServiceSession * curr;
677 for (curr = tail; NULL != curr; curr = curr->prev) {
678 // if the key matches, and the element_count is same
679 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
680 && (curr->total == element_count)) {
681 // if incoming state is NULL OR is same as state of the queued request
682 if ((NULL == state) || (curr->state == *state)) {
683 // if peerid is NULL OR same as the peer Id in the queued request
685 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
686 // matches and is not an already terminated session
696 * Safely frees ALL memory areas referenced by a session.
698 * @param session - the session to free elements from
701 free_session_variables (struct ServiceSession * session)
706 for (i = 0; i < session->used; i++)
707 if (session->a[i]) gcry_mpi_release (session->a[i]);
708 GNUNET_free (session->a);
712 GNUNET_free (session->mask);
713 session->mask = NULL;
716 for (i = 0; i < session->used; i++)
717 if (session->r[i]) gcry_mpi_release (session->r[i]);
718 GNUNET_free (session->r);
721 if (session->r_prime) {
722 for (i = 0; i < session->used; i++)
723 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
724 GNUNET_free (session->r_prime);
725 session->r_prime = NULL;
728 gcry_mpi_release (session->s);
732 if (session->s_prime) {
733 gcry_mpi_release (session->s_prime);
734 session->s_prime = NULL;
737 if (session->product) {
738 gcry_mpi_release (session->product);
739 session->product = NULL;
742 if (session->remote_pubkey) {
743 gcry_sexp_release (session->remote_pubkey);
744 session->remote_pubkey = NULL;
747 if (session->vector) {
748 GNUNET_free_non_null (session->vector);
752 ///////////////////////////////////////////////////////////////////////////////
753 // Event and Message Handlers
754 ///////////////////////////////////////////////////////////////////////////////
758 * A client disconnected.
760 * Remove the associated session(s), release data structures
761 * and cancel pending outgoing transmissions to the client.
762 * if the session has not yet completed, we also cancel Alice's request to Bob.
764 * @param cls closure, NULL
765 * @param client identification of the client
768 handle_client_disconnect (void *cls,
769 struct GNUNET_SERVER_Client *client)
771 struct ServiceSession *session;
774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
775 _ ("Client (%p) disconnected from us.\n"), client);
779 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
782 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
784 if (!(session->role == BOB && session->state == FINALIZED)) {
785 //we MUST terminate any client message underway
786 if (session->service_transmit_handle && session->channel)
787 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
788 if (session->channel && session->state == WAITING_FOR_SERVICE_RESPONSE)
789 GNUNET_MESH_channel_destroy (session->channel);
791 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
792 GNUNET_SCHEDULER_cancel (session->client_notification_task);
793 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
795 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
796 GNUNET_SCHEDULER_cancel (session->service_request_task);
797 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
799 if (NULL != session->client_transmit_handle) {
800 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
801 session->client_transmit_handle = NULL;
803 free_session_variables (session);
804 GNUNET_free (session);
809 * Notify the client that the session has succeeded or failed completely.
810 * This message gets sent to
811 * * alice's client if bob disconnected or to
812 * * bob's client if the operation completed or alice disconnected
814 * @param cls the associated client session
815 * @param tc the task context handed to us by the scheduler, unused
818 prepare_client_end_notification (void * cls,
819 const struct GNUNET_SCHEDULER_TaskContext * tc)
821 struct ServiceSession * session = cls;
822 struct GNUNET_SCALARPRODUCT_client_response * msg;
824 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
826 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
827 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
828 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
829 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
830 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
831 // signal error if not signalized, positive result-range field but zero length.
832 msg->product_length = htonl (0);
833 msg->range = (session->state == FINALIZED) ? 0 : -1;
835 session->msg = &msg->header;
837 //transmit this message to our client
838 session->client_transmit_handle =
839 GNUNET_SERVER_notify_transmit_ready (session->client,
840 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
841 GNUNET_TIME_UNIT_FOREVER_REL,
845 // if we could not even queue our request, something is wrong
846 if (NULL == session->client_transmit_handle) {
847 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
848 // usually gets freed by do_send_message
853 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
855 free_session_variables (session);
860 * prepare the response we will send to alice or bobs' clients.
861 * in Bobs case the product will be NULL.
863 * @param cls the session associated with our client.
864 * @param tc the task context handed to us by the scheduler, unused
867 prepare_client_response (void *cls,
868 const struct GNUNET_SCHEDULER_TaskContext *tc)
870 struct ServiceSession * session = cls;
871 struct GNUNET_SCALARPRODUCT_client_response * msg;
872 unsigned char * product_exported = NULL;
873 size_t product_length = 0;
874 uint32_t msg_length = 0;
879 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
881 if (session->product) {
882 gcry_mpi_t value = gcry_mpi_new (0);
884 sign = gcry_mpi_cmp_ui (session->product, 0);
885 // libgcrypt can not handle a print of a negative number
886 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
888 gcry_mpi_sub (value, value, session->product);
892 gcry_mpi_add (value, value, session->product);
897 gcry_mpi_release (session->product);
898 session->product = NULL;
900 // get representation as string
902 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
906 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
908 range = -1; // signal error with product-length = 0 and range = -1
910 gcry_mpi_release (value);
913 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
914 msg = GNUNET_malloc (msg_length);
915 msg->key = session->key;
916 msg->peer = session->peer;
917 if (product_exported != NULL)
919 memcpy (&msg[1], product_exported, product_length);
920 GNUNET_free (product_exported);
922 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
923 msg->header.size = htons (msg_length);
925 msg->product_length = htonl (product_length);
927 session->msg = (struct GNUNET_MessageHeader *) msg;
928 //transmit this message to our client
929 session->client_transmit_handle =
930 GNUNET_SERVER_notify_transmit_ready (session->client,
932 GNUNET_TIME_UNIT_FOREVER_REL,
935 if (NULL == session->client_transmit_handle) {
936 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
937 _ ("Could not send message to client (%p)!\n"),
939 session->client = NULL;
940 // callback was not called!
945 // gracefully sent message, just terminate session structure
946 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
947 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
949 GNUNET_h2s (&session->key));
950 free_session_variables (session);
955 * Send a multipart chunk of a service response from bob to alice.
956 * This element only contains the two permutations of R, R'.
958 * @param cls the associated service session
961 prepare_service_response_multipart (void *cls)
963 struct ServiceSession * session = cls;
964 unsigned char * current;
965 unsigned char * element_exported;
966 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
970 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
972 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
973 todo_count = session->used - session->transferred;
975 if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
976 // send the currently possible maximum chunk, we always transfer both permutations
977 todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
979 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
980 msg = GNUNET_malloc (msg_length);
981 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
982 msg->header.size = htons (msg_length);
983 msg->multipart_element_count = htonl (todo_count);
985 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
986 current = (unsigned char *) &msg[1];
988 for (i = session->transferred; i < session->transferred + todo_count; i++) {
990 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
991 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
992 element_exported, PAILLIER_ELEMENT_LENGTH,
995 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
996 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
997 current += PAILLIER_ELEMENT_LENGTH;
999 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1000 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1001 element_exported, PAILLIER_ELEMENT_LENGTH,
1003 session->r_prime[i]));
1004 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1005 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1006 current += PAILLIER_ELEMENT_LENGTH;
1008 GNUNET_free (element_exported);
1009 for (i = session->transferred; i < session->transferred; i++) {
1010 gcry_mpi_release (session->r_prime[i]);
1011 session->r_prime[i] = NULL;
1012 gcry_mpi_release (session->r[i]);
1013 session->r[i] = NULL;
1015 session->transferred += todo_count;
1016 session->msg = (struct GNUNET_MessageHeader *) msg;
1017 session->service_transmit_handle =
1018 GNUNET_MESH_notify_transmit_ready (session->channel,
1020 GNUNET_TIME_UNIT_FOREVER_REL,
1024 //disconnect our client
1025 if (NULL == session->service_transmit_handle) {
1026 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1027 session->state = FINALIZED;
1029 session->response->client_notification_task =
1030 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1034 if (session->transferred != session->used)
1036 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1039 session->state = FINALIZED;
1040 GNUNET_free(session->r);
1041 GNUNET_free(session->r_prime);
1042 session->r_prime = NULL;
1050 * generates the response message to be sent to alice after computing
1051 * the values (1), (2), S and S'
1052 * (1)[]: $E_A(a_{pi(i)}) times E_A(- r_{pi(i)} - b_{pi(i)}) &= E_A(a_{pi(i)} - r_{pi(i)} - b_{pi(i)})$
1053 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1054 * S: $S := E_A(sum (r_i + b_i)^2)$
1055 * S': $S' := E_A(sum r_i^2)$
1057 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
1058 * @param s_prime S': $S' := E_A(sum r_i^2)$
1059 * @param session the associated requesting session with alice
1060 * @return #GNUNET_NO if we could not send our message
1061 * #GNUNET_OK if the operation succeeded
1064 prepare_service_response (gcry_mpi_t s,
1066 struct ServiceSession * session)
1068 struct GNUNET_SCALARPRODUCT_service_response * msg;
1069 uint32_t msg_length = 0;
1070 unsigned char * current = NULL;
1071 unsigned char * element_exported = NULL;
1072 size_t element_length = 0;
1075 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
1076 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
1078 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used * PAILLIER_ELEMENT_LENGTH) { //kp, kq
1079 msg_length += +2 * session->used * PAILLIER_ELEMENT_LENGTH;
1080 session->transferred = session->used;
1083 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
1086 msg = GNUNET_malloc (msg_length);
1088 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
1089 msg->header.size = htons (msg_length);
1090 msg->total_element_count = htonl (session->total);
1091 msg->used_element_count = htonl (session->used);
1092 msg->contained_element_count = htonl (session->transferred);
1093 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1094 current = (unsigned char *) &msg[1];
1096 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1097 // 4 times the same logics with slight variations.
1098 // doesn't really justify having 2 functions for that
1099 // so i put it into blocks to enhance readability
1101 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1102 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1103 element_exported, PAILLIER_ELEMENT_LENGTH,
1106 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1107 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1108 current += PAILLIER_ELEMENT_LENGTH;
1111 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1112 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1113 element_exported, PAILLIER_ELEMENT_LENGTH,
1116 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1117 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1118 current += PAILLIER_ELEMENT_LENGTH;
1121 for (i = 0; i < session->transferred; i++) {
1123 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1124 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1125 element_exported, PAILLIER_ELEMENT_LENGTH,
1128 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1129 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1130 current += PAILLIER_ELEMENT_LENGTH;
1132 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1133 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1134 element_exported, PAILLIER_ELEMENT_LENGTH,
1136 session->r_prime[i]));
1137 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1138 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1139 current += PAILLIER_ELEMENT_LENGTH;
1142 GNUNET_free (element_exported);
1143 for (i = 0; i < session->transferred; i++) {
1144 gcry_mpi_release (session->r_prime[i]);
1145 session->r_prime[i] = NULL;
1146 gcry_mpi_release (session->r[i]);
1147 session->r[i] = NULL;
1149 gcry_mpi_release (s);
1151 gcry_mpi_release (s_prime);
1152 session->s_prime = NULL;
1154 session->msg = (struct GNUNET_MessageHeader *) msg;
1155 session->service_transmit_handle =
1156 GNUNET_MESH_notify_transmit_ready (session->channel,
1158 GNUNET_TIME_UNIT_FOREVER_REL,
1162 //disconnect our client
1163 if (NULL == session->service_transmit_handle) {
1164 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1165 session->state = FINALIZED;
1167 session->response->client_notification_task =
1168 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1172 if (session->transferred != session->used)
1174 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1177 session->state = FINALIZED;
1178 GNUNET_free(session->r);
1179 GNUNET_free(session->r_prime);
1180 session->r_prime = NULL;
1190 * compute the values
1191 * (1)[]: $E_A(a_{pi(i)}) otimes E_A(- r_{pi(i)} - b_{pi(i)}) &= E_A(a_{pi(i)} - r_{pi(i)} - b_{pi(i)})$
1192 * (2)[]: $E_A(a_{pi'(i)}) otimes E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1193 * S: $S := E_A(sum (r_i + b_i)^2)$
1194 * S': $S' := E_A(sum r_i^2)$
1196 * @param request the requesting session + bob's requesting peer
1197 * @param response the responding session + bob's client handle
1198 * @return GNUNET_SYSERR if the computation failed
1199 * GNUNET_OK if everything went well.
1202 compute_service_response (struct ServiceSession * request,
1203 struct ServiceSession * response)
1207 int ret = GNUNET_SYSERR;
1211 gcry_mpi_t * rand = NULL;
1212 gcry_mpi_t * r = NULL;
1213 gcry_mpi_t * r_prime = NULL;
1216 gcry_mpi_t * a_pi_prime;
1218 gcry_mpi_t * rand_pi;
1219 gcry_mpi_t * rand_pi_prime;
1220 gcry_mpi_t s = NULL;
1221 gcry_mpi_t s_prime = NULL;
1222 gcry_mpi_t remote_n = NULL;
1223 gcry_mpi_t remote_nsquare;
1224 gcry_mpi_t remote_g = NULL;
1225 gcry_sexp_t tmp_exp;
1228 count = request->used;
1230 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1231 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1232 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1233 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1234 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1235 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1237 // convert responder session to from long to mpi
1238 for (i = 0, j = 0; i < response->total && j < count; i++)
1240 if (request->mask[i / 8] & (1 << (i % 8)))
1242 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1243 // long to gcry_mpi_t
1244 if (0 > response->vector[i])
1246 b[j] = gcry_mpi_new (0);
1247 gcry_mpi_sub_ui (b[j], b[j], value);
1250 b[j] = gcry_mpi_set_ui (NULL, value);
1255 GNUNET_free (response->vector);
1256 response->vector = NULL;
1258 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1260 GNUNET_break_op (0);
1261 gcry_sexp_release (request->remote_pubkey);
1262 request->remote_pubkey = NULL;
1265 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1268 gcry_sexp_release (tmp_exp);
1271 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1272 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1273 gcry_sexp_release (tmp_exp);
1274 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1275 gcry_sexp_release (request->remote_pubkey);
1276 request->remote_pubkey = NULL;
1278 GNUNET_break_op (0);
1279 gcry_mpi_release (remote_n);
1282 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1285 gcry_mpi_release (remote_n);
1286 gcry_sexp_release (tmp_exp);
1289 gcry_sexp_release (tmp_exp);
1291 // generate r, p and q
1292 rand = initialize_mpi_vector (count);
1293 for (i = 0; i < count; i++)
1297 svalue = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
1299 // long to gcry_mpi_t
1301 gcry_mpi_sub_ui (rand[i],
1305 rand[i] = gcry_mpi_set_ui (rand[i], svalue);
1307 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1308 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1309 //initialize the result vectors
1310 r = initialize_mpi_vector (count);
1311 r_prime = initialize_mpi_vector (count);
1313 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1314 // those values, thus we can work with the references
1315 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1316 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1317 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1318 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1319 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1321 // generate p and q permutations for a, b and r
1322 GNUNET_assert (permute_vector (a_pi, p, count));
1323 GNUNET_assert (permute_vector (b_pi, p, count));
1324 GNUNET_assert (permute_vector (rand_pi, p, count));
1325 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1326 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1328 // encrypt the element
1329 // for the sake of readability I decided to have dedicated permutation
1330 // vectors, which get rid of all the lookups in p/q.
1331 // however, ap/aq are not absolutely necessary but are just abstraction
1332 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1333 for (i = 0; i < count; i++)
1335 // E(S - r_pi - b_pi)
1336 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1337 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1338 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1340 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1341 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1345 GNUNET_free (rand_pi);
1347 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1348 for (i = 0; i < count; i++)
1351 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1352 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1354 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1355 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1357 GNUNET_free (a_pi_prime);
1358 GNUNET_free (rand_pi_prime);
1361 request->r_prime = r_prime;
1362 request->response = response;
1364 // Calculate S' = E(SUM( r_i^2 ))
1365 s_prime = compute_square_sum (rand, count);
1366 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1368 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1369 for (i = 0; i < count; i++) {
1370 gcry_mpi_add (rand[i], rand[i], b[i]);
1372 s = compute_square_sum (rand, count);
1373 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1374 gcry_mpi_release (remote_n);
1375 gcry_mpi_release (remote_g);
1376 gcry_mpi_release (remote_nsquare);
1378 // release r and tmp
1379 for (i = 0; i < count; i++)
1380 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1381 gcry_mpi_release (rand[i]);
1383 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1384 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1385 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1386 GNUNET_i2s (&request->peer));
1391 for (i = 0; i < count; i++)
1393 gcry_mpi_release (b[i]);
1394 gcry_mpi_release (request->a[i]);
1398 GNUNET_free (request->a);
1408 * Send a multi part chunk of a service request from alice to bob.
1409 * This element only contains a part of the elements-vector (session->a[]),
1410 * mask and public key set have to be contained within the first message
1412 * This allows a ~32kbit key length while using 32000 elements or 62000 elements per request.
1414 * @param cls the associated service session
1417 prepare_service_request_multipart (void *cls)
1419 struct ServiceSession * session = cls;
1420 unsigned char * current;
1421 unsigned char * element_exported;
1422 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1425 uint32_t msg_length;
1426 uint32_t todo_count;
1427 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1431 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1432 todo_count = session->used - session->transferred;
1434 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1435 // send the currently possible maximum chunk
1436 todo_count = MULTIPART_ELEMENT_CAPACITY;
1438 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1439 msg = GNUNET_malloc (msg_length);
1440 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1441 msg->header.size = htons (msg_length);
1442 msg->multipart_element_count = htonl (todo_count);
1444 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1445 a = gcry_mpi_new (KEYBITS * 2);
1446 current = (unsigned char *) &msg[1];
1447 // encrypt our vector and generate string representations
1448 for (i = session->last_processed, j = 0; i < session->total; i++)
1450 // is this a used element?
1451 if (session->mask[i / 8] & 1 << (i % 8)) {
1452 if (todo_count <= j)
1453 break; //reached end of this message, can't include more
1455 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1456 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1458 a = gcry_mpi_set_ui (a, 0);
1459 // long to gcry_mpi_t
1460 if (session->vector[i] < 0)
1461 gcry_mpi_sub_ui (a, a, value);
1463 gcry_mpi_add_ui (a, a, value);
1465 session->a[session->transferred + j++] = gcry_mpi_set (NULL, a);
1466 gcry_mpi_add (a, a, my_offset);
1467 encrypt_element (a, a, my_g, my_n, my_nsquare);
1469 // get representation as string
1470 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1471 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1472 element_exported, PAILLIER_ELEMENT_LENGTH,
1476 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1477 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1479 // copy over to the message
1480 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1481 current += PAILLIER_ELEMENT_LENGTH;
1484 gcry_mpi_release (a);
1485 GNUNET_free (element_exported);
1486 session->transferred += todo_count;
1488 session->msg = (struct GNUNET_MessageHeader *) msg;
1489 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1491 //transmit via mesh messaging
1492 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->channel, GNUNET_YES,
1493 GNUNET_TIME_UNIT_FOREVER_REL,
1497 if (!session->service_transmit_handle) {
1498 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to channel!\n"));
1500 session->msg = NULL;
1501 session->client_notification_task =
1502 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1506 if (session->transferred != session->used) {
1507 session->last_processed = i;
1511 session->state = WAITING_FOR_SERVICE_RESPONSE;
1516 * Executed by Alice, fills in a service-request message and sends it to the given peer
1518 * @param cls the session associated with this request
1519 * @param tc task context handed over by scheduler, unsued
1522 prepare_service_request (void *cls,
1523 const struct GNUNET_SCHEDULER_TaskContext *tc)
1525 struct ServiceSession * session = cls;
1526 unsigned char * current;
1527 unsigned char * element_exported;
1528 struct GNUNET_SCALARPRODUCT_service_request * msg;
1531 uint32_t msg_length;
1532 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1536 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1538 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new channel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1540 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1541 +session->mask_length
1542 + my_pubkey_external_length;
1544 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used * PAILLIER_ELEMENT_LENGTH) {
1545 msg_length += session->used * PAILLIER_ELEMENT_LENGTH;
1546 session->transferred = session->used;
1549 //create a multipart msg, first we calculate a new msg size for the head msg
1550 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1553 msg = GNUNET_malloc (msg_length);
1554 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1555 msg->total_element_count = htonl (session->used);
1556 msg->contained_element_count = htonl (session->transferred);
1557 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1558 msg->mask_length = htonl (session->mask_length);
1559 msg->pk_length = htonl (my_pubkey_external_length);
1560 msg->element_count = htonl (session->total);
1561 msg->header.size = htons (msg_length);
1563 // fill in the payload
1564 current = (unsigned char *) &msg[1];
1565 // copy over the mask
1566 memcpy (current, session->mask, session->mask_length);
1567 // copy over our public key
1568 current += session->mask_length;
1569 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1570 current += my_pubkey_external_length;
1572 // now copy over the element vector
1573 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1574 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
1575 a = gcry_mpi_new (KEYBITS * 2);
1576 // encrypt our vector and generate string representations
1577 for (i = 0, j = 0; i < session->total; i++) {
1578 // if this is a used element...
1579 if (session->mask[i / 8] & 1 << (i % 8)) {
1580 if (session->transferred <= j)
1581 break; //reached end of this message, can't include more
1583 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1584 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1586 a = gcry_mpi_set_ui (a, 0);
1587 // long to gcry_mpi_t
1588 if (session->vector[i] < 0)
1589 gcry_mpi_sub_ui (a, a, value);
1591 gcry_mpi_add_ui (a, a, value);
1593 session->a[j++] = gcry_mpi_set (NULL, a);
1594 gcry_mpi_add (a, a, my_offset);
1595 encrypt_element (a, a, my_g, my_n, my_nsquare);
1597 // get representation as string
1598 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1599 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1600 element_exported, PAILLIER_ELEMENT_LENGTH,
1604 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1605 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1607 // copy over to the message
1608 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1609 current += PAILLIER_ELEMENT_LENGTH;
1612 gcry_mpi_release (a);
1613 GNUNET_free (element_exported);
1615 session->msg = (struct GNUNET_MessageHeader *) msg;
1616 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1618 //transmit via mesh messaging
1619 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->channel, GNUNET_YES,
1620 GNUNET_TIME_UNIT_FOREVER_REL,
1624 if (!session->service_transmit_handle) {
1625 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to channel!\n"));
1627 session->msg = NULL;
1628 session->client_notification_task =
1629 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1633 if (session->transferred != session->used) {
1634 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1635 session->last_processed = i;
1638 //singlepart message
1639 session->state = WAITING_FOR_SERVICE_RESPONSE;
1644 * Handler for a client request message.
1645 * Can either be type A or B
1646 * A: request-initiation to compute a scalar product with a peer
1647 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1649 * @param cls closure
1650 * @param client identification of the client
1651 * @param message the actual message
1654 handle_client_request (void *cls,
1655 struct GNUNET_SERVER_Client *client,
1656 const struct GNUNET_MessageHeader *message)
1658 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1659 struct ServiceSession * session;
1660 uint32_t element_count;
1661 uint32_t mask_length;
1666 // only one concurrent session per client connection allowed, simplifies logics a lot...
1667 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1668 if ((NULL != session) && (session->state != FINALIZED)) {
1669 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1672 else if (NULL != session) {
1673 // old session is already completed, clean it up
1674 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1675 free_session_variables (session);
1676 GNUNET_free (session);
1679 //we need at least a peer and one message id to compare
1680 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1681 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1682 _ ("Too short message received from client!\n"));
1683 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1687 msg_type = ntohs (msg->header.type);
1688 element_count = ntohl (msg->element_count);
1689 mask_length = ntohl (msg->mask_length);
1691 //sanity check: is the message as long as the message_count fields suggests?
1692 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1693 || (0 == element_count)) {
1694 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1695 _ ("Invalid message received from client, session information incorrect!\n"));
1696 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1700 // do we have a duplicate session here already?
1701 if (NULL != find_matching_session (from_client_tail,
1705 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1706 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1707 GNUNET_h2s (&msg->key));
1708 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1712 session = GNUNET_new (struct ServiceSession);
1713 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1714 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1715 session->client = client;
1716 session->total = element_count;
1717 session->mask_length = mask_length;
1718 // get our transaction key
1719 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1720 //allocate memory for vector and encrypted vector
1721 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1722 vector = (int32_t *) & msg[1];
1724 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726 _ ("Got client-request-session with key %s, preparing channel to remote service.\n"),
1727 GNUNET_h2s (&session->key));
1729 session->role = ALICE;
1731 session->mask = GNUNET_malloc (mask_length);
1732 memcpy (session->mask, &vector[element_count], mask_length);
1734 // copy over the elements
1736 for (i = 0; i < element_count; i++) {
1737 session->vector[i] = ntohl (vector[i]);
1738 if (session->vector[i] == 0)
1739 session->mask[i / 8] &= ~(1 << (i % 8));
1740 if (session->mask[i / 8] & (1 << (i % 8)))
1744 if (0 == session->used) {
1745 GNUNET_break_op (0);
1746 GNUNET_free (session->vector);
1747 GNUNET_free (session);
1748 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1751 //session with ourself makes no sense!
1752 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1754 GNUNET_free (session->vector);
1755 GNUNET_free (session);
1756 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1760 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1761 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1762 _ ("Creating new channel for session with key %s.\n"),
1763 GNUNET_h2s (&session->key));
1764 session->channel = GNUNET_MESH_channel_create (my_mesh, session,
1766 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1767 GNUNET_MESH_OPTION_RELIABLE);
1768 //prepare_service_request, channel_peer_disconnect_handler,
1769 if (!session->channel) {
1771 GNUNET_free (session->vector);
1772 GNUNET_free (session);
1773 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1776 GNUNET_SERVER_client_set_user_context (client, session);
1777 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1779 session->state = CLIENT_REQUEST_RECEIVED;
1780 session->service_request_task =
1781 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1786 struct ServiceSession * requesting_session;
1787 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1789 session->role = BOB;
1790 session->mask = NULL;
1791 // copy over the elements
1792 session->used = element_count;
1793 for (i = 0; i < element_count; i++)
1794 session->vector[i] = ntohl (vector[i]);
1795 session->state = CLIENT_RESPONSE_RECEIVED;
1797 GNUNET_SERVER_client_set_user_context (client, session);
1798 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1800 //check if service queue contains a matching request
1801 requesting_session = find_matching_session (from_service_tail,
1804 &needed_state, NULL);
1805 if (NULL != requesting_session) {
1806 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s and a matching service-request-session set, processing.\n"), GNUNET_h2s (&session->key));
1807 if (GNUNET_OK != compute_service_response (requesting_session, session))
1808 session->client_notification_task =
1809 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1814 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s but NO matching service-request-session set, queuing element for later use.\n"), GNUNET_h2s (&session->key));
1815 // no matching session exists yet, store the response
1816 // for later processing by handle_service_request()
1819 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1824 * Function called for inbound channels.
1826 * @param cls closure
1827 * @param channel new handle to the channel
1828 * @param initiator peer that started the channel
1829 * @param port unused
1830 * @param options unused
1832 * @return session associated with the channel
1835 channel_incoming_handler (void *cls,
1836 struct GNUNET_MESH_Channel *channel,
1837 const struct GNUNET_PeerIdentity *initiator,
1838 uint32_t port, enum MeshOption options)
1840 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("New incoming channel from peer %s.\n"), GNUNET_i2s (initiator));
1844 c->peer = *initiator;
1845 c->channel = channel;
1847 c->state = WAITING_FOR_SERVICE_REQUEST;
1853 * Function called whenever a channel is destroyed. Should clean up
1854 * any associated state.
1856 * It must NOT call GNUNET_MESH_channel_destroy on the channel.
1858 * @param cls closure (set from GNUNET_MESH_connect)
1859 * @param channel connection to the other end (henceforth invalid)
1860 * @param channel_ctx place where local state associated
1861 * with the channel is stored
1864 channel_destruction_handler (void *cls,
1865 const struct GNUNET_MESH_Channel *channel,
1868 struct ServiceSession * session = channel_ctx;
1869 struct ServiceSession * client_session;
1870 struct ServiceSession * curr;
1872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1873 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1874 GNUNET_h2s (&session->key),
1875 GNUNET_i2s (&session->peer));
1876 if (ALICE == session->role) {
1877 // as we have only one peer connected in each session, just remove the session
1879 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1880 session->channel = NULL;
1881 // if this happened before we received the answer, we must terminate the session
1882 session->client_notification_task =
1883 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1887 else { //(BOB == session->role) service session
1888 // remove the session, unless it has already been dequeued, but somehow still active
1889 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1890 // scenario: disconnect before alice can send her message to bob.
1891 for (curr = from_service_head; NULL != curr; curr = curr->next)
1892 if (curr == session) {
1893 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1896 // there is a client waiting for this service session, terminate it, too!
1897 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1898 client_session = find_matching_session (from_client_tail,
1902 free_session_variables (session);
1903 GNUNET_free (session);
1905 // the client has to check if it was waiting for a result
1906 // or if it was a responder, no point in adding more statefulness
1907 if (client_session && (!do_shutdown)) {
1908 client_session->state = FINALIZED;
1909 client_session->client_notification_task =
1910 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1918 * Compute our scalar product, done by Alice
1920 * @param session - the session associated with this computation
1921 * @return product as MPI, never NULL
1924 compute_scalar_product (struct ServiceSession * session)
1935 count = session->used;
1936 // due to the introduced static offset S, we now also have to remove this
1937 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1938 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1939 for (i = 0; i < count; i++) {
1940 decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1941 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1942 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1943 decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1944 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1945 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1948 // calculate t = sum(ai)
1949 t = compute_square_sum (session->a, count);
1952 u = gcry_mpi_new (0);
1953 tmp = compute_square_sum (session->r, count);
1954 gcry_mpi_sub (u, u, tmp);
1955 gcry_mpi_release (tmp);
1958 u_prime = gcry_mpi_new (0);
1959 tmp = compute_square_sum (session->r_prime, count);
1960 gcry_mpi_sub (u_prime, u_prime, tmp);
1962 GNUNET_assert (p = gcry_mpi_new (0));
1963 GNUNET_assert (p_prime = gcry_mpi_new (0));
1966 decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1967 decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1970 gcry_mpi_add (p, session->s, t);
1971 gcry_mpi_add (p, p, u);
1974 gcry_mpi_add (p_prime, session->s_prime, t);
1975 gcry_mpi_add (p_prime, p_prime, u_prime);
1977 gcry_mpi_release (t);
1978 gcry_mpi_release (u);
1979 gcry_mpi_release (u_prime);
1982 gcry_mpi_sub (p, p, p_prime);
1983 gcry_mpi_release (p_prime);
1984 tmp = gcry_mpi_set_ui (tmp, 2);
1985 gcry_mpi_div (p, NULL, p, tmp, 0);
1987 gcry_mpi_release (tmp);
1988 for (i = 0; i < count; i++)
1989 gcry_mpi_release (session->a[i]);
1990 GNUNET_free (session->a);
1998 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
2000 * @param cls closure (set from #GNUNET_MESH_connect)
2001 * @param channel connection to the other end
2002 * @param channel_ctx place to store local state associated with the channel
2003 * @param message the actual message
2004 * @return #GNUNET_OK to keep the connection open,
2005 * #GNUNET_SYSERR to close it (signal serious error)
2008 handle_service_request_multipart (void *cls,
2009 struct GNUNET_MESH_Channel * channel,
2011 const struct GNUNET_MessageHeader * message)
2013 struct ServiceSession * session;
2014 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2015 uint32_t used_elements;
2016 uint32_t contained_elements = 0;
2017 uint32_t msg_length;
2018 unsigned char * current;
2022 // are we in the correct state?
2023 session = (struct ServiceSession *) * channel_ctx;
2024 if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2027 // shorter than minimum?
2028 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2031 used_elements = session->used;
2032 contained_elements = ntohl (msg->multipart_element_count);
2033 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2034 +contained_elements * PAILLIER_ELEMENT_LENGTH;
2036 if ((ntohs (msg->header.size) != msg_length)
2037 || (used_elements < contained_elements + session->transferred)) {
2040 current = (unsigned char *) &msg[1];
2041 if (contained_elements != 0) {
2042 // Convert each vector element to MPI_value
2043 for (i = session->transferred; i < session->transferred + contained_elements; i++) {
2045 if (0 != (rc = gcry_mpi_scan (&session->a[i],
2047 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2048 PAILLIER_ELEMENT_LENGTH,
2050 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2054 session->transferred += contained_elements;
2056 if (session->transferred == used_elements) {
2057 // single part finished
2058 session->state = SERVICE_REQUEST_RECEIVED;
2059 if (session->response) {
2060 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2061 if (GNUNET_OK != compute_service_response (session, session->response)) {
2062 //something went wrong, remove it again...
2067 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2070 // multipart message
2076 // and notify our client-session that we could not complete the session
2077 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2078 if (session->response)
2079 // we just found the responder session in this queue
2080 session->response->client_notification_task =
2081 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2083 free_session_variables (session);
2084 GNUNET_free (session);
2085 return GNUNET_SYSERR;
2090 * Handle a request from another service to calculate a scalarproduct with us.
2092 * @param cls closure (set from #GNUNET_MESH_connect)
2093 * @param channel connection to the other end
2094 * @param channel_ctx place to store local state associated with the channel
2095 * @param message the actual message
2096 * @return #GNUNET_OK to keep the connection open,
2097 * #GNUNET_SYSERR to close it (signal serious error)
2100 handle_service_request (void *cls,
2101 struct GNUNET_MESH_Channel * channel,
2103 const struct GNUNET_MessageHeader * message)
2105 struct ServiceSession * session;
2106 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2107 uint32_t mask_length;
2109 uint32_t used_elements;
2110 uint32_t contained_elements = 0;
2111 uint32_t element_count;
2112 uint32_t msg_length;
2113 unsigned char * current;
2116 enum SessionState needed_state;
2118 session = (struct ServiceSession *) * channel_ctx;
2119 if (WAITING_FOR_SERVICE_REQUEST != session->state) {
2122 // Check if message was sent by me, which would be bad!
2123 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2124 GNUNET_free (session);
2126 return GNUNET_SYSERR;
2128 // shorter than expected?
2129 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2130 GNUNET_free (session);
2131 GNUNET_break_op (0);
2132 return GNUNET_SYSERR;
2134 mask_length = ntohl (msg->mask_length);
2135 pk_length = ntohl (msg->pk_length);
2136 used_elements = ntohl (msg->total_element_count);
2137 contained_elements = ntohl (msg->contained_element_count);
2138 element_count = ntohl (msg->element_count);
2139 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2140 +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2142 //sanity check: is the message as long as the message_count fields suggests?
2143 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2144 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2146 GNUNET_free (session);
2147 GNUNET_break_op (0);
2148 return GNUNET_SYSERR;
2150 if (find_matching_session (from_service_tail,
2155 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2156 GNUNET_free (session);
2157 return GNUNET_SYSERR;
2160 session->total = element_count;
2161 session->used = used_elements;
2162 session->transferred = contained_elements;
2163 session->channel = channel;
2166 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2167 current = (unsigned char *) &msg[1];
2168 //preserve the mask, we will need that later on
2169 session->mask = GNUNET_malloc (mask_length);
2170 memcpy (session->mask, current, mask_length);
2172 current += mask_length;
2174 //convert the publickey to sexp
2175 if (0 != (rc = gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))) {
2176 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_sexp_new", rc);
2177 GNUNET_free (session->mask);
2178 GNUNET_free (session);
2179 return GNUNET_SYSERR;
2181 current += pk_length;
2182 //check if service queue contains a matching request
2183 needed_state = CLIENT_RESPONSE_RECEIVED;
2184 session->response = find_matching_session (from_client_tail,
2187 &needed_state, NULL);
2189 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2190 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2191 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2192 if (contained_elements != 0) {
2193 // Convert each vector element to MPI_value
2194 for (i = 0; i < contained_elements; i++) {
2196 if (0 != (rc = gcry_mpi_scan (&session->a[i],
2198 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2199 PAILLIER_ELEMENT_LENGTH,
2201 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2205 if (contained_elements == used_elements) {
2206 // single part finished
2207 session->state = SERVICE_REQUEST_RECEIVED;
2208 if (session->response) {
2209 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2210 if (GNUNET_OK != compute_service_response (session, session->response)) {
2211 //something went wrong, remove it again...
2216 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2219 // multipart message
2224 GNUNET_break_op (0);
2225 if ((NULL != session->next) || (NULL != session->prev) || (from_service_head == session))
2226 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2227 // and notify our client-session that we could not complete the session
2228 if (session->response)
2229 // we just found the responder session in this queue
2230 session->response->client_notification_task =
2231 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2233 free_session_variables (session);
2234 return GNUNET_SYSERR;
2239 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2241 * @param cls closure (set from #GNUNET_MESH_connect)
2242 * @param channel connection to the other end
2243 * @param channel_ctx place to store local state associated with the channel
2244 * @param message the actual message
2245 * @return #GNUNET_OK to keep the connection open,
2246 * #GNUNET_SYSERR to close it (signal serious error)
2249 handle_service_response_multipart (void *cls,
2250 struct GNUNET_MESH_Channel * channel,
2252 const struct GNUNET_MessageHeader * message)
2254 struct ServiceSession * session;
2255 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2256 unsigned char * current;
2259 uint32_t contained = 0;
2261 size_t required_size;
2264 GNUNET_assert (NULL != message);
2265 // are we in the correct state?
2266 session = (struct ServiceSession *) * channel_ctx;
2267 if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2270 msg_size = ntohs (msg->header.size);
2271 required_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message) + 2 * PAILLIER_ELEMENT_LENGTH;
2272 // shorter than minimum?
2273 if (required_size > msg_size) {
2276 contained = ntohl (msg->multipart_element_count);
2277 required_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2278 + 2 * contained * PAILLIER_ELEMENT_LENGTH;
2279 //sanity check: is the message as long as the message_count fields suggests?
2280 if ((required_size != msg_size) || (session->used < session->transferred + contained)) {
2283 current = (unsigned char *) &msg[1];
2284 // Convert each k[][perm] to its MPI_value
2285 for (i = 0; i < contained; i++) {
2286 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2287 PAILLIER_ELEMENT_LENGTH, &read))) {
2288 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2291 current += PAILLIER_ELEMENT_LENGTH;
2292 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2293 PAILLIER_ELEMENT_LENGTH, &read))) {
2294 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2297 current += PAILLIER_ELEMENT_LENGTH;
2299 session->transferred += contained;
2300 if (session->transferred != session->used)
2302 session->state = SERVICE_RESPONSE_RECEIVED;
2303 session->product = compute_scalar_product (session); //never NULL
2306 GNUNET_break_op (NULL != session->product);
2308 // send message with product to client
2309 if (ALICE == session->role){
2310 session->state = FINALIZED;
2311 session->channel = NULL;
2312 session->client_notification_task =
2313 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2316 // the channel has done its job, terminate our connection and the channel
2317 // the peer will be notified that the channel was destroyed via channel_destruction_handler
2318 // just close the connection, as recommended by Christian
2319 return GNUNET_SYSERR;
2324 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2326 * @param cls closure (set from #GNUNET_MESH_connect)
2327 * @param channel connection to the other end
2328 * @param channel_ctx place to store local state associated with the channel
2329 * @param message the actual message
2330 * @return #GNUNET_OK to keep the connection open,
2331 * #GNUNET_SYSERR to close it (we are done)
2334 handle_service_response (void *cls,
2335 struct GNUNET_MESH_Channel * channel,
2337 const struct GNUNET_MessageHeader * message)
2339 struct ServiceSession * session;
2340 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2341 unsigned char * current;
2344 uint32_t contained = 0;
2346 size_t required_size;
2349 GNUNET_assert (NULL != message);
2350 session = (struct ServiceSession *) * channel_ctx;
2351 // are we in the correct state?
2352 if (WAITING_FOR_SERVICE_RESPONSE != session->state) {
2355 //we need at least a full message without elements attached
2356 msg_size = ntohs (msg->header.size);
2357 required_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response) + 2 * PAILLIER_ELEMENT_LENGTH;
2359 if (required_size > msg_size) {
2362 contained = ntohl (msg->contained_element_count);
2363 required_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2364 + 2 * contained * PAILLIER_ELEMENT_LENGTH
2365 + 2 * PAILLIER_ELEMENT_LENGTH;
2366 //sanity check: is the message as long as the message_count fields suggests?
2367 if ((msg_size != required_size) || (session->used < contained)) {
2370 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2371 session->transferred = contained;
2373 current = (unsigned char *) &msg[1];
2374 if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2375 PAILLIER_ELEMENT_LENGTH, &read))) {
2376 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2379 current += PAILLIER_ELEMENT_LENGTH;
2381 if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2382 PAILLIER_ELEMENT_LENGTH, &read))) {
2383 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2386 current += PAILLIER_ELEMENT_LENGTH;
2387 session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2388 session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2389 // Convert each k[][perm] to its MPI_value
2390 for (i = 0; i < contained; i++) {
2391 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2392 PAILLIER_ELEMENT_LENGTH, &read))) {
2393 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2396 current += PAILLIER_ELEMENT_LENGTH;
2397 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2398 PAILLIER_ELEMENT_LENGTH, &read))) {
2399 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2402 current += PAILLIER_ELEMENT_LENGTH;
2404 if (session->transferred != session->used)
2405 return GNUNET_OK; //wait for the other multipart chunks
2407 session->state = SERVICE_RESPONSE_RECEIVED;
2408 session->product = compute_scalar_product (session); //never NULL
2411 GNUNET_break_op (NULL != session->product);
2412 // send message with product to client
2413 if (ALICE == session->role){
2414 session->state = FINALIZED;
2415 session->channel = NULL;
2416 session->client_notification_task =
2417 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2420 // the channel has done its job, terminate our connection and the channel
2421 // the peer will be notified that the channel was destroyed via channel_destruction_handler
2422 // just close the connection, as recommended by Christian
2423 return GNUNET_SYSERR;
2428 * Task run during shutdown.
2434 shutdown_task (void *cls,
2435 const struct GNUNET_SCHEDULER_TaskContext *tc)
2437 struct ServiceSession * session;
2438 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2440 do_shutdown = GNUNET_YES;
2442 // terminate all owned open channels.
2443 for (session = from_client_head; NULL != session; session = session->next) {
2444 if ((FINALIZED != session->state) && (NULL != session->channel)) {
2445 GNUNET_MESH_channel_destroy (session->channel);
2446 session->channel = NULL;
2448 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2449 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2450 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2452 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2453 GNUNET_SCHEDULER_cancel (session->service_request_task);
2454 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2456 if (NULL != session->client) {
2457 GNUNET_SERVER_client_disconnect (session->client);
2458 session->client = NULL;
2461 for (session = from_service_head; NULL != session; session = session->next)
2462 if (NULL != session->channel) {
2463 GNUNET_MESH_channel_destroy (session->channel);
2464 session->channel = NULL;
2468 GNUNET_MESH_disconnect (my_mesh);
2475 * Initialization of the program and message handlers
2477 * @param cls closure
2478 * @param server the initialized server
2479 * @param c configuration to use
2483 struct GNUNET_SERVER_Handle *server,
2484 const struct GNUNET_CONFIGURATION_Handle *c)
2486 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2487 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2488 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2491 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2492 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2493 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2494 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2495 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2498 static const uint32_t ports[] = {
2499 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2502 //generate private/public key set
2503 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2505 // register server callbacks and disconnect handler
2506 GNUNET_SERVER_add_handlers (server, server_handlers);
2507 GNUNET_SERVER_disconnect_notify (server,
2508 &handle_client_disconnect,
2510 GNUNET_break (GNUNET_OK ==
2511 GNUNET_CRYPTO_get_peer_identity (c,
2513 my_mesh = GNUNET_MESH_connect (c, NULL,
2514 &channel_incoming_handler,
2515 &channel_destruction_handler,
2516 mesh_handlers, ports);
2518 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2519 GNUNET_SCHEDULER_shutdown ();
2522 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2523 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2530 * The main function for the scalarproduct service.
2532 * @param argc number of arguments from the command line
2533 * @param argv command line arguments
2534 * @return 0 ok, 1 on error
2537 main (int argc, char *const *argv)
2539 return (GNUNET_OK ==
2540 GNUNET_SERVICE_run (argc, argv,
2542 GNUNET_SERVICE_OPTION_NONE,
2543 &run, NULL)) ? 0 : 1;
2546 /* end of gnunet-service-scalarproduct.c */