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 ///////////////////////////////////////////////////////////////////////////////
43 * state a session can be in
47 CLIENT_REQUEST_RECEIVED,
48 WAITING_FOR_BOBS_CONNECT,
49 CLIENT_RESPONSE_RECEIVED,
50 WAITING_FOR_SERVICE_REQUEST,
51 WAITING_FOR_MULTIPART_TRANSMISSION,
52 WAITING_FOR_SERVICE_RESPONSE,
53 SERVICE_REQUEST_RECEIVED,
54 SERVICE_RESPONSE_RECEIVED,
59 * role a peer in a session can assume
68 * A scalarproduct session which tracks:
70 * a request form the client to our final response.
72 * a request from a service to us(service).
77 * the role this peer has
82 * session information is kept in a DLL
84 struct ServiceSession *next;
87 * session information is kept in a DLL
89 struct ServiceSession *prev;
92 * (hopefully) unique transaction ID
94 struct GNUNET_HashCode key;
97 * state of the session
99 enum SessionState state;
102 * Alice or Bob's peerID
104 struct GNUNET_PeerIdentity peer;
107 * the client this request is related to
109 struct GNUNET_SERVER_Client * client;
112 * The message to send
114 struct GNUNET_MessageHeader * msg;
117 * how many elements we were supplied with from the client
119 uint32_t element_count;
122 * how many elements actually are used after applying the mask
124 uint32_t used_element_count;
127 * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
129 uint32_t transferred_element_count;
132 * index of the last transferred element for multipart messages
134 uint32_t last_processed_element;
137 * how many bytes the mask is long.
138 * just for convenience so we don't have to re-re-re calculate it each time
140 uint32_t mask_length;
143 * all the vector elements we received
148 * mask of which elements to check
150 unsigned char * mask;
153 * Public key of the remote service, only used by bob
155 gcry_sexp_t remote_pubkey;
158 * E(ai)(Bob) or ai(Alice) after applying the mask
163 * Bob's permutation p of R
168 * Bob's permutation q of R
170 gcry_mpi_t * r_prime;
173 * Bobs matching response session from the client
175 struct ServiceSession * response;
178 * The computed scalar
183 * My transmit handle for the current message to a alice/bob
185 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
188 * My transmit handle for the current message to the client
190 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
193 * tunnel-handle associated with our mesh handle
195 struct GNUNET_MESH_Tunnel * tunnel;
197 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
199 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
202 ///////////////////////////////////////////////////////////////////////////////
204 ///////////////////////////////////////////////////////////////////////////////
208 * Handle to the core service (NULL until we've connected to it).
210 static struct GNUNET_MESH_Handle *my_mesh;
213 * The identity of this host.
215 static struct GNUNET_PeerIdentity me;
218 * Service's own public key represented as string
220 static unsigned char * my_pubkey_external;
223 * Service's own public key represented as string
225 static uint32_t my_pubkey_external_length = 0;
230 static gcry_mpi_t my_n;
233 * Service's own n^2 (kept for performance)
235 static gcry_mpi_t my_nsquare;
238 * Service's own public exponent
240 static gcry_mpi_t my_g;
243 * Service's own private multiplier
245 static gcry_mpi_t my_mu;
248 * Service's own private exponent
250 static gcry_mpi_t my_lambda;
253 * Service's offset for values that could possibly be negative but are plaintext for encryption.
255 static gcry_mpi_t my_offset;
258 * Head of our double linked list for client-requests sent to us.
259 * for all of these elements we calculate a scalar product with a remote peer
260 * split between service->service and client->service for simplicity
262 static struct ServiceSession * from_client_head;
264 * Tail of our double linked list for client-requests sent to us.
265 * for all of these elements we calculate a scalar product with a remote peer
266 * split between service->service and client->service for simplicity
268 static struct ServiceSession * from_client_tail;
271 * Head of our double linked list for service-requests sent to us.
272 * for all of these elements we help the requesting service in calculating a scalar product
273 * split between service->service and client->service for simplicity
275 static struct ServiceSession * from_service_head;
278 * Tail of our double linked list for service-requests sent to us.
279 * for all of these elements we help the requesting service in calculating a scalar product
280 * split between service->service and client->service for simplicity
282 static struct ServiceSession * from_service_tail;
285 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
287 static int do_shutdown;
289 ///////////////////////////////////////////////////////////////////////////////
291 ///////////////////////////////////////////////////////////////////////////////
294 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
299 gcry_sexp_t gen_params;
301 gcry_sexp_t tmp_sexp;
310 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
311 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
312 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
315 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
316 gcry_sexp_release (gen_params);
318 // get n and d of our publickey as MPI
319 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
320 GNUNET_assert (tmp_sexp);
321 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
322 gcry_sexp_release (tmp_sexp);
323 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
324 GNUNET_assert (tmp_sexp);
325 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
326 gcry_sexp_release (tmp_sexp);
327 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
328 GNUNET_assert (tmp_sexp);
329 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
330 gcry_sexp_release (key);
332 tmp1 = gcry_mpi_new (0);
333 tmp2 = gcry_mpi_new (0);
334 gcd = gcry_mpi_new (0);
335 my_g = gcry_mpi_new (0);
336 my_mu = gcry_mpi_new (0);
337 my_nsquare = gcry_mpi_new (0);
338 my_lambda = gcry_mpi_new (0);
341 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
342 gcry_mpi_sub_ui (tmp1, p, 1);
343 gcry_mpi_sub_ui (tmp2, q, 1);
344 gcry_mpi_gcd (gcd, tmp1, tmp2);
345 gcry_mpi_set (my_lambda, tmp1);
346 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
347 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
350 gcry_mpi_mul (my_nsquare, my_n, my_n);
354 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
355 // g must be smaller than n^2
356 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
359 // g must have gcd == 1 with n^2
360 gcry_mpi_gcd (gcd, my_g, my_nsquare);
362 while (gcry_mpi_cmp_ui (gcd, 1));
364 // is this a valid g?
365 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
366 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
367 gcry_mpi_sub_ui (tmp1, tmp1, 1);
368 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
369 gcry_mpi_gcd (gcd, tmp1, my_n);
371 while (gcry_mpi_cmp_ui (gcd, 1));
373 // calculate our mu based on g and n.
374 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
375 gcry_mpi_invm (my_mu, tmp1, my_n);
377 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
378 "(public-key (paillier (n %M)(g %M)))",
381 // get the length of this sexpression
382 my_pubkey_external_length = gcry_sexp_sprint (key,
387 GNUNET_assert (my_pubkey_external_length > 0);
388 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
390 // convert the sexpression to canonical format
391 gcry_sexp_sprint (key,
394 my_pubkey_external_length);
396 gcry_sexp_release (key);
398 // offset has to be sufficiently small to allow computation of:
399 // m1+m2 mod n == (S + a) + (S + b) mod n,
400 // if we have more complex operations, this factor needs to be lowered
401 my_offset = gcry_mpi_new (KEYBITS / 3);
402 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
408 * If target != size, move target bytes to the
409 * end of the size-sized buffer and zero out the
410 * first target-size bytes.
412 * @param buf original buffer
413 * @param size number of bytes in the buffer
414 * @param target target size of the buffer
417 adjust (unsigned char *buf, size_t size, size_t target)
420 memmove (&buf[target - size], buf, size);
421 memset (buf, 0, target - size);
426 * encrypts an element using the paillier crypto system
428 * @param c ciphertext (output)
430 * @param g the public base
431 * @param n the module from which which r is chosen (Z*_n)
432 * @param n_square the module for encryption, for performance reasons.
435 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
439 GNUNET_assert (tmp = gcry_mpi_new (0));
441 while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
442 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
443 // r must be 1 < r < n
446 gcry_mpi_powm (c, g, m, n_square);
447 gcry_mpi_powm (tmp, tmp, n, n_square);
448 gcry_mpi_mulm (c, tmp, c, n_square);
450 gcry_mpi_release (tmp);
454 * decrypts an element using the paillier crypto system
456 * @param m plaintext (output)
457 * @param c the ciphertext
458 * @param mu the modifier to correct encryption
459 * @param lambda the private exponent
460 * @param n the outer module for decryption
461 * @param n_square the inner module for decryption
464 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)
466 gcry_mpi_powm (m, c, lambda, n_square);
467 gcry_mpi_sub_ui (m, m, 1);
468 gcry_mpi_div (m, NULL, m, n, 0);
469 gcry_mpi_mulm (m, m, mu, n);
473 * computes the square sum over a vector of a given length.
475 * @param vector the vector to encrypt
476 * @param length the length of the vector
477 * @return an MPI value containing the calculated sum, never NULL
480 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
486 GNUNET_assert (sum = gcry_mpi_new (0));
487 GNUNET_assert (elem = gcry_mpi_new (0));
489 // calculare E(sum (ai ^ 2), publickey)
490 for (i = 0; i < length; i++) {
491 gcry_mpi_mul (elem, vector[i], vector[i]);
492 gcry_mpi_add (sum, sum, elem);
494 gcry_mpi_release (elem);
501 prepare_service_request_multipart (void *cls,
502 const struct GNUNET_SCHEDULER_TaskContext *tc);
504 prepare_service_response_multipart (void *cls,
505 const struct GNUNET_SCHEDULER_TaskContext *tc);
508 * Primitive callback for copying over a message, as they
509 * usually are too complex to be handled in the callback itself.
510 * clears a session-callback, if a session was handed over and the transmit handle was stored
512 * @param cls the message object
513 * @param size the size of the buffer we got
514 * @param buf the buffer to copy the message to
515 * @return 0 if we couldn't copy, else the size copied over
518 do_send_message (void *cls, size_t size, void *buf)
520 struct ServiceSession * session = cls;
525 if (ntohs (session->msg->size) == size) {
526 memcpy (buf, session->msg, size);
530 switch (ntohs (session->msg->type))
532 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
533 session->state = FINALIZED;
534 session->client_transmit_handle = NULL;
536 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
537 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
539 session->service_transmit_handle = NULL;
540 // reset flags for sending
541 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
542 prepare_service_request_multipart (session, NULL);
543 //TODO we have sent a message and now need to trigger trigger the next multipart message sending
545 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
546 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
548 session->service_transmit_handle = NULL;
549 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
550 prepare_service_response_multipart (session, NULL);
553 session->service_transmit_handle = NULL;
556 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
557 "Sent a message of type %hu.\n",
558 ntohs (session->msg->type));
559 GNUNET_free (session->msg);
566 * initializes a new vector with fresh MPI values (=0) of a given length
568 * @param length of the vector to create
569 * @return the initialized vector, never NULL
572 initialize_mpi_vector (uint32_t length)
575 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
577 for (i = 0; i < length; i++)
578 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
583 * permutes an MPI vector according to the given permutation vector
585 * @param vector the vector to permuted
586 * @param perm the permutation to use
587 * @param length the length of the vectors
588 * @return the permuted vector (same as input), never NULL
591 permute_vector (gcry_mpi_t * vector,
595 gcry_mpi_t tmp[length];
598 GNUNET_assert (length > 0);
601 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
603 // permute vector according to given
604 for (i = 0; i < length; i++)
605 vector[i] = tmp[perm[i]];
611 * Populate a vector with random integer values and convert them to
613 * @param length the length of the vector we must generate
614 * @return an array of MPI values with random values
617 generate_random_vector (uint32_t length)
619 gcry_mpi_t * random_vector;
623 random_vector = initialize_mpi_vector (length);
624 for (i = 0; i < length; i++) {
625 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
627 // long to gcry_mpi_t
629 gcry_mpi_sub_ui (random_vector[i],
633 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
636 return random_vector;
640 * Finds a not terminated client/service session in the
641 * given DLL based on session key, element count and state.
643 * @param tail - the tail of the DLL
644 * @param my - the session to compare it to
645 * @return a pointer to a matching session,
648 static struct ServiceSession *
649 find_matching_session (struct ServiceSession * tail,
650 const struct GNUNET_HashCode * key,
651 uint32_t element_count,
652 enum SessionState * state,
653 const struct GNUNET_PeerIdentity * peerid)
655 struct ServiceSession * curr;
657 for (curr = tail; NULL != curr; curr = curr->prev) {
658 // if the key matches, and the element_count is same
659 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
660 && (curr->element_count == element_count)) {
661 // if incoming state is NULL OR is same as state of the queued request
662 if ((NULL == state) || (curr->state == *state)) {
663 // if peerid is NULL OR same as the peer Id in the queued request
665 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
666 // matches and is not an already terminated session
676 free_session (struct ServiceSession * session)
681 for (i = 0; i < session->used_element_count; i++)
682 gcry_mpi_release (session->a[i]);
684 GNUNET_free (session->a);
686 if (session->product)
687 gcry_mpi_release (session->product);
689 if (session->remote_pubkey)
690 gcry_sexp_release (session->remote_pubkey);
692 GNUNET_free_non_null (session->vector);
693 GNUNET_free (session);
695 ///////////////////////////////////////////////////////////////////////////////
696 // Event and Message Handlers
697 ///////////////////////////////////////////////////////////////////////////////
700 * A client disconnected.
702 * Remove the associated session(s), release datastructures
703 * and cancel pending outgoing transmissions to the client.
704 * if the session has not yet completed, we also cancel Alice's request to Bob.
706 * @param cls closure, NULL
707 * @param client identification of the client
710 handle_client_disconnect (void *cls,
711 struct GNUNET_SERVER_Client *client)
713 struct ServiceSession *session;
717 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
721 _ ("Client (%p) disconnected from us.\n"), client);
722 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
724 if (!(session->role == BOB && session->state == FINALIZED)) {
725 //we MUST terminate any client message underway
726 if (session->service_transmit_handle && session->tunnel)
727 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
728 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
729 GNUNET_MESH_tunnel_destroy (session->tunnel);
731 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
732 GNUNET_SCHEDULER_cancel (session->client_notification_task);
733 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
735 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
736 GNUNET_SCHEDULER_cancel (session->service_request_task);
737 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
739 if (NULL != session->client_transmit_handle) {
740 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
741 session->client_transmit_handle = NULL;
743 free_session (session);
747 * Notify the client that the session has succeeded or failed completely.
748 * This message gets sent to
749 * * alice's client if bob disconnected or to
750 * * bob's client if the operation completed or alice disconnected
752 * @param client_session the associated client session
753 * @return GNUNET_NO, if we could not notify the client
754 * GNUNET_YES if we notified it.
757 prepare_client_end_notification (void * cls,
758 const struct GNUNET_SCHEDULER_TaskContext * tc)
760 struct ServiceSession * session = cls;
761 struct GNUNET_SCALARPRODUCT_client_response * msg;
763 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
765 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
766 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
767 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
768 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
769 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
770 // signal error if not signalized, positive result-range field but zero length.
771 msg->product_length = htonl (0);
772 msg->range = (session->state == FINALIZED) ? 0 : -1;
774 session->msg = &msg->header;
776 //transmit this message to our client
777 session->client_transmit_handle =
778 GNUNET_SERVER_notify_transmit_ready (session->client,
779 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
780 GNUNET_TIME_UNIT_FOREVER_REL,
784 // if we could not even queue our request, something is wrong
785 if (NULL == session->client_transmit_handle) {
786 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
787 // usually gets freed by do_send_message
792 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
797 prepare_service_response_multipart (void *cls,
798 const struct GNUNET_SCHEDULER_TaskContext *tc)
800 struct ServiceSession * session = cls;
801 unsigned char * current;
802 unsigned char * element_exported;
803 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
807 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
809 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
810 todo_count = session->used_element_count - session->transferred_element_count;
812 if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
813 // send the currently possible maximum chunk, we always transfer both permutations
814 todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
816 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
817 msg = GNUNET_malloc (msg_length);
818 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
819 msg->header.size = htons (msg_length);
820 msg->multipart_element_count = htonl (todo_count);
822 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
823 current = (unsigned char *) &msg[1];
825 for (i = session->transferred_element_count; i < session->transferred_element_count + todo_count; i++) {
827 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
828 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
829 element_exported, PAILLIER_ELEMENT_LENGTH,
832 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
833 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
834 current += PAILLIER_ELEMENT_LENGTH;
836 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
837 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
838 element_exported, PAILLIER_ELEMENT_LENGTH,
840 session->r_prime[i]));
841 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
842 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
843 current += PAILLIER_ELEMENT_LENGTH;
845 GNUNET_free (element_exported);
846 for (i = session->transferred_element_count; i < session->transferred_element_count; i++) {
847 gcry_mpi_release (session->r_prime[i]);
848 gcry_mpi_release (session->r[i]);
850 session->transferred_element_count += todo_count;
851 session->msg = (struct GNUNET_MessageHeader *) msg;
852 session->service_transmit_handle =
853 GNUNET_MESH_notify_transmit_ready (session->tunnel,
855 GNUNET_TIME_UNIT_FOREVER_REL,
859 //disconnect our client
860 if (NULL == session->service_transmit_handle) {
861 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
862 session->state = FINALIZED;
864 session->response->client_notification_task =
865 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
869 if (session->transferred_element_count != session->used_element_count)
871 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
874 session->state = FINALIZED;
879 * generates the response message to be sent to alice after computing
880 * the values (1), (2), S and S'
881 * (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)})$
882 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
883 * S: $S := E_A(sum (r_i + b_i)^2)$
884 * S': $S' := E_A(sum r_i^2)$
886 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
887 * @param s_prime S': $S' := E_A(sum r_i^2)$
888 * @param session the associated requesting session with alice
889 * @return GNUNET_NO if we could not send our message
890 * GNUNET_OK if the operation succeeded
893 prepare_service_response (gcry_mpi_t s,
895 struct ServiceSession * session)
897 struct GNUNET_SCALARPRODUCT_service_response * msg;
898 uint32_t msg_length = 0;
899 unsigned char * current = NULL;
900 unsigned char * element_exported = NULL;
901 size_t element_length = 0;
904 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
905 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
907 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH) { //kp, kq
908 msg_length += +2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH;
909 session->transferred_element_count = session->used_element_count;
912 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
915 msg = GNUNET_malloc (msg_length);
917 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
918 msg->header.size = htons (msg_length);
919 msg->total_element_count = htonl (session->element_count);
920 msg->contained_element_count = htonl (session->used_element_count);
921 msg->contained_element_count = htonl (session->transferred_element_count);
922 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
923 current = (unsigned char *) &msg[1];
925 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
926 // 4 times the same logics with slight variations.
927 // doesn't really justify having 2 functions for that
928 // so i put it into blocks to enhance readability
930 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
931 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
932 element_exported, PAILLIER_ELEMENT_LENGTH,
935 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
936 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
937 current += PAILLIER_ELEMENT_LENGTH;
940 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
941 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
942 element_exported, PAILLIER_ELEMENT_LENGTH,
945 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
946 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
947 current += PAILLIER_ELEMENT_LENGTH;
950 for (i = 0; i < session->transferred_element_count; i++) {
952 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
953 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
954 element_exported, PAILLIER_ELEMENT_LENGTH,
957 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
958 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
959 current += PAILLIER_ELEMENT_LENGTH;
961 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
962 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
963 element_exported, PAILLIER_ELEMENT_LENGTH,
965 session->r_prime[i]));
966 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
967 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
968 current += PAILLIER_ELEMENT_LENGTH;
971 GNUNET_free (element_exported);
972 for (i = 0; i < session->transferred_element_count; i++) {
973 gcry_mpi_release (session->r_prime[i]);
974 gcry_mpi_release (session->r[i]);
976 gcry_mpi_release (s);
977 gcry_mpi_release (s_prime);
979 session->msg = (struct GNUNET_MessageHeader *) msg;
980 session->service_transmit_handle =
981 GNUNET_MESH_notify_transmit_ready (session->tunnel,
983 GNUNET_TIME_UNIT_FOREVER_REL,
987 //disconnect our client
988 if (NULL == session->service_transmit_handle) {
989 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
990 session->state = FINALIZED;
992 session->response->client_notification_task =
993 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
997 if (session->transferred_element_count != session->used_element_count)
999 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1002 session->state = FINALIZED;
1009 * compute the values
1010 * (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)})$
1011 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1012 * S: $S := E_A(\sum (r_i + b_i)^2)$
1013 * S': $S' := E_A(\sum r_i^2)$
1015 * @param request the requesting session + bob's requesting peer
1016 * @param response the responding session + bob's client handle
1017 * @return GNUNET_SYSERR if the computation failed
1018 * GNUNET_OK if everything went well.
1021 compute_service_response (struct ServiceSession * request,
1022 struct ServiceSession * response)
1026 int ret = GNUNET_SYSERR;
1030 gcry_mpi_t * rand = NULL;
1031 gcry_mpi_t * r = NULL;
1032 gcry_mpi_t * r_prime = NULL;
1035 gcry_mpi_t * a_pi_prime;
1037 gcry_mpi_t * rand_pi;
1038 gcry_mpi_t * rand_pi_prime;
1039 gcry_mpi_t s = NULL;
1040 gcry_mpi_t s_prime = NULL;
1041 gcry_mpi_t remote_n = NULL;
1042 gcry_mpi_t remote_nsquare;
1043 gcry_mpi_t remote_g = NULL;
1044 gcry_sexp_t tmp_exp;
1047 count = request->used_element_count;
1049 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1050 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1051 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1052 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1053 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1054 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1056 // convert responder session to from long to mpi
1057 for (i = 0, j = 0; i < response->element_count && j < count; i++) {
1058 if (request->mask[i / 8] & (1 << (i % 8))) {
1059 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1060 // long to gcry_mpi_t
1061 if (0 > response->vector[i]) {
1062 b[j] = gcry_mpi_new (0);
1063 gcry_mpi_sub_ui (b[j], b[j], value);
1066 b[j] = gcry_mpi_set_ui (NULL, value);
1071 GNUNET_free (response->vector);
1072 response->vector = NULL;
1074 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1076 GNUNET_break_op (0);
1077 gcry_sexp_release (request->remote_pubkey);
1078 request->remote_pubkey = NULL;
1081 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1084 gcry_sexp_release (tmp_exp);
1087 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1088 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1089 gcry_sexp_release (tmp_exp);
1090 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1091 gcry_sexp_release (request->remote_pubkey);
1092 request->remote_pubkey = NULL;
1094 GNUNET_break_op (0);
1095 gcry_mpi_release (remote_n);
1098 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1101 gcry_mpi_release (remote_n);
1102 gcry_sexp_release (tmp_exp);
1105 gcry_sexp_release (tmp_exp);
1107 // generate r, p and q
1108 rand = generate_random_vector (count);
1109 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1110 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1111 //initialize the result vectors
1112 r = initialize_mpi_vector (count);
1113 r_prime = initialize_mpi_vector (count);
1115 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1116 // those values, thus we can work with the references
1117 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1118 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1119 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1120 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1121 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1123 // generate p and q permutations for a, b and r
1124 GNUNET_assert (permute_vector (a_pi, p, count));
1125 GNUNET_assert (permute_vector (b_pi, p, count));
1126 GNUNET_assert (permute_vector (rand_pi, p, count));
1127 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1128 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1130 // encrypt the element
1131 // for the sake of readability I decided to have dedicated permutation
1132 // vectors, which get rid of all the lookups in p/q.
1133 // however, ap/aq are not absolutely necessary but are just abstraction
1134 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1135 for (i = 0; i < count; i++) {
1136 // E(S - r_pi - b_pi)
1137 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1138 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1139 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1141 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1142 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1146 GNUNET_free (rand_pi);
1148 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1149 for (i = 0; i < count; i++) {
1151 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1152 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1154 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1155 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1157 GNUNET_free (a_pi_prime);
1158 GNUNET_free (rand_pi_prime);
1161 request->r_prime = r_prime;
1162 request->response = response;
1164 // Calculate S' = E(SUM( r_i^2 ))
1165 s_prime = compute_square_sum (rand, count);
1166 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1168 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1169 for (i = 0; i < count; i++) {
1170 gcry_mpi_add (rand[i], rand[i], b[i]);
1172 s = compute_square_sum (rand, count);
1173 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1174 gcry_mpi_release (remote_n);
1175 gcry_mpi_release (remote_g);
1176 gcry_mpi_release (remote_nsquare);
1178 // release r and tmp
1179 for (i = 0; i < count; i++)
1180 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1181 gcry_mpi_release (rand[i]);
1183 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1184 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1185 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1186 GNUNET_i2s (&request->peer));
1191 for (i = 0; i < count; i++) {
1192 gcry_mpi_release (b[i]);
1193 gcry_mpi_release (request->a[i]);
1197 GNUNET_free (request->a);
1204 prepare_service_request_multipart (void *cls,
1205 const struct GNUNET_SCHEDULER_TaskContext *tc)
1207 struct ServiceSession * session = cls;
1208 unsigned char * current;
1209 unsigned char * element_exported;
1210 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1213 uint32_t msg_length;
1214 uint32_t todo_count;
1215 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1219 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1220 todo_count = session->used_element_count - session->transferred_element_count;
1222 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1223 // send the currently possible maximum chunk
1224 todo_count = MULTIPART_ELEMENT_CAPACITY;
1226 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1227 msg = GNUNET_malloc (msg_length);
1228 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1229 msg->header.size = htons (msg_length);
1230 msg->multipart_element_count = htonl (todo_count);
1232 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1233 a = gcry_mpi_new (KEYBITS * 2);
1234 current = (unsigned char *) &msg[1];
1235 // encrypt our vector and generate string representations
1236 for (i = session->last_processed_element, j = 0; i < session->element_count; i++) {
1237 // is this a used element?
1238 if (session->mask[i / 8] & 1 << (i % 8)) {
1239 if (todo_count <= j)
1240 break; //reached end of this message, can't include more
1242 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1243 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1245 a = gcry_mpi_set_ui (a, 0);
1246 // long to gcry_mpi_t
1247 if (session->vector[i] < 0)
1248 gcry_mpi_sub_ui (a, a, value);
1250 gcry_mpi_add_ui (a, a, value);
1252 session->a[session->transferred_element_count + j++] = gcry_mpi_set (NULL, a);
1253 gcry_mpi_add (a, a, my_offset);
1254 encrypt_element (a, a, my_g, my_n, my_nsquare);
1256 // get representation as string
1257 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1258 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1259 element_exported, PAILLIER_ELEMENT_LENGTH,
1263 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1264 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1266 // copy over to the message
1267 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1268 current += PAILLIER_ELEMENT_LENGTH;
1271 gcry_mpi_release (a);
1272 GNUNET_free (element_exported);
1273 session->transferred_element_count += todo_count;
1275 session->msg = (struct GNUNET_MessageHeader *) msg;
1276 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1278 //transmit via mesh messaging
1279 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1280 GNUNET_TIME_UNIT_FOREVER_REL,
1284 if (!session->service_transmit_handle) {
1285 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1287 session->msg = NULL;
1288 session->client_notification_task =
1289 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1293 if (session->transferred_element_count != session->used_element_count) {
1294 session->last_processed_element = i;
1298 session->state = WAITING_FOR_SERVICE_RESPONSE;
1302 * Executed by Alice, fills in a service-request message and sends it to the given peer
1304 * @param session the session associated with this request, then also holds the CORE-handle
1305 * @return #GNUNET_SYSERR if we could not send the message
1306 * #GNUNET_NO if the message was too large
1307 * #GNUNET_OK if we sent it
1310 prepare_service_request (void *cls,
1311 const struct GNUNET_SCHEDULER_TaskContext *tc)
1313 struct ServiceSession * session = cls;
1314 unsigned char * current;
1315 unsigned char * element_exported;
1316 struct GNUNET_SCALARPRODUCT_service_request * msg;
1319 uint32_t msg_length;
1320 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1324 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1328 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1329 +session->mask_length
1330 + my_pubkey_external_length;
1332 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used_element_count * PAILLIER_ELEMENT_LENGTH) {
1333 msg_length += session->used_element_count * PAILLIER_ELEMENT_LENGTH;
1334 session->transferred_element_count = session->used_element_count;
1337 //create a multipart msg, first we calculate a new msg size for the head msg
1338 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1341 msg = GNUNET_malloc (msg_length);
1342 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1343 msg->total_element_count = htonl (session->used_element_count);
1344 msg->contained_element_count = htonl (session->transferred_element_count);
1345 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1346 msg->mask_length = htonl (session->mask_length);
1347 msg->pk_length = htonl (my_pubkey_external_length);
1348 msg->element_count = htonl (session->element_count);
1349 msg->header.size = htons (msg_length);
1351 // fill in the payload
1352 current = (unsigned char *) &msg[1];
1353 // copy over the mask
1354 memcpy (current, session->mask, session->mask_length);
1355 // copy over our public key
1356 current += session->mask_length;
1357 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1358 current += my_pubkey_external_length;
1360 // now copy over the element vector
1361 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1362 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1363 a = gcry_mpi_new (KEYBITS * 2);
1364 // encrypt our vector and generate string representations
1365 for (i = 0, j = 0; i < session->element_count; i++) {
1366 // if this is a used element...
1367 if (session->mask[i / 8] & 1 << (i % 8)) {
1368 if (session->transferred_element_count <= j)
1369 break; //reached end of this message, can't include more
1371 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1372 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1374 a = gcry_mpi_set_ui (a, 0);
1375 // long to gcry_mpi_t
1376 if (session->vector[i] < 0)
1377 gcry_mpi_sub_ui (a, a, value);
1379 gcry_mpi_add_ui (a, a, value);
1381 session->a[j++] = gcry_mpi_set (NULL, a);
1382 gcry_mpi_add (a, a, my_offset);
1383 encrypt_element (a, a, my_g, my_n, my_nsquare);
1385 // get representation as string
1386 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1387 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1388 element_exported, PAILLIER_ELEMENT_LENGTH,
1392 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1393 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1395 // copy over to the message
1396 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1397 current += PAILLIER_ELEMENT_LENGTH;
1400 gcry_mpi_release (a);
1401 GNUNET_free (element_exported);
1403 session->msg = (struct GNUNET_MessageHeader *) msg;
1404 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1406 //transmit via mesh messaging
1407 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1408 GNUNET_TIME_UNIT_FOREVER_REL,
1412 if (!session->service_transmit_handle) {
1413 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1415 session->msg = NULL;
1416 session->client_notification_task =
1417 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1421 if (session->transferred_element_count != session->used_element_count) {
1422 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1423 session->last_processed_element = i;
1426 //singlepart message
1427 session->state = WAITING_FOR_SERVICE_RESPONSE;
1431 * Handler for a client request message.
1432 * Can either be type A or B
1433 * A: request-initiation to compute a scalar product with a peer
1434 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1436 * @param cls closure
1437 * @param client identification of the client
1438 * @param message the actual message
1441 handle_client_request (void *cls,
1442 struct GNUNET_SERVER_Client *client,
1443 const struct GNUNET_MessageHeader *message)
1445 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1446 struct ServiceSession * session;
1447 uint32_t element_count;
1448 uint32_t mask_length;
1453 // only one concurrent session per client connection allowed, simplifies logics a lot...
1454 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1455 if ((NULL != session) && (session->state != FINALIZED)) {
1456 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1459 else if (NULL != session) {
1460 // old session is already completed, clean it up
1461 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1462 free_session (session);
1465 //we need at least a peer and one message id to compare
1466 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1467 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1468 _ ("Too short message received from client!\n"));
1469 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1473 msg_type = ntohs (msg->header.type);
1474 element_count = ntohl (msg->element_count);
1475 mask_length = ntohl (msg->mask_length);
1477 //sanity check: is the message as long as the message_count fields suggests?
1478 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1479 || (0 == element_count)) {
1480 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1481 _ ("Invalid message received from client, session information incorrect!\n"));
1482 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1486 // do we have a duplicate session here already?
1487 if (NULL != find_matching_session (from_client_tail,
1491 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1492 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1493 GNUNET_h2s (&msg->key));
1494 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1498 session = GNUNET_new (struct ServiceSession);
1499 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1500 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1501 session->client = client;
1502 session->element_count = element_count;
1503 session->mask_length = mask_length;
1504 // get our transaction key
1505 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1506 //allocate memory for vector and encrypted vector
1507 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1508 vector = (int32_t *) & msg[1];
1510 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1512 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1513 GNUNET_h2s (&session->key));
1515 session->role = ALICE;
1517 session->mask = GNUNET_malloc (mask_length);
1518 memcpy (session->mask, &vector[element_count], mask_length);
1520 // copy over the elements
1521 session->used_element_count = 0;
1522 for (i = 0; i < element_count; i++) {
1523 session->vector[i] = ntohl (vector[i]);
1524 if (session->vector[i] == 0)
1525 session->mask[i / 8] &= ~(1 << (i % 8));
1526 if (session->mask[i / 8] & (1 << (i % 8)))
1527 session->used_element_count++;
1530 if (0 == session->used_element_count) {
1531 GNUNET_break_op (0);
1532 GNUNET_free (session->vector);
1533 GNUNET_free (session);
1534 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1537 //session with ourself makes no sense!
1538 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1540 GNUNET_free (session->vector);
1541 GNUNET_free (session);
1542 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1546 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1547 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1548 _ ("Creating new tunnel to for session with key %s.\n"),
1549 GNUNET_h2s (&session->key));
1550 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1552 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1555 //prepare_service_request, tunnel_peer_disconnect_handler,
1556 if (!session->tunnel) {
1558 GNUNET_free (session->vector);
1559 GNUNET_free (session);
1560 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1563 GNUNET_SERVER_client_set_user_context (client, session);
1564 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1566 session->state = CLIENT_REQUEST_RECEIVED;
1567 session->service_request_task =
1568 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1573 struct ServiceSession * requesting_session;
1574 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1576 session->role = BOB;
1577 session->mask = NULL;
1578 // copy over the elements
1579 session->used_element_count = element_count;
1580 for (i = 0; i < element_count; i++)
1581 session->vector[i] = ntohl (vector[i]);
1582 session->state = CLIENT_RESPONSE_RECEIVED;
1584 GNUNET_SERVER_client_set_user_context (client, session);
1585 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1587 //check if service queue contains a matching request
1588 requesting_session = find_matching_session (from_service_tail,
1590 session->element_count,
1591 &needed_state, NULL);
1592 if (NULL != requesting_session) {
1593 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));
1594 if (GNUNET_OK != compute_service_response (requesting_session, session))
1595 session->client_notification_task =
1596 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1601 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));
1602 // no matching session exists yet, store the response
1603 // for later processing by handle_service_request()
1606 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1610 * Function called for inbound tunnels.
1612 * @param cls closure
1613 * @param tunnel new handle to the tunnel
1614 * @param initiator peer that started the tunnel
1615 * @param atsi performance information for the tunnel
1616 * @return initial tunnel context for the tunnel
1617 * (can be NULL -- that's not an error)
1620 tunnel_incoming_handler (void *cls,
1621 struct GNUNET_MESH_Tunnel *tunnel,
1622 const struct GNUNET_PeerIdentity *initiator,
1625 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1627 c->peer = *initiator;
1630 c->state = WAITING_FOR_SERVICE_REQUEST;
1635 * Function called whenever a tunnel is destroyed. Should clean up
1636 * any associated state.
1638 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1640 * @param cls closure (set from GNUNET_MESH_connect)
1641 * @param tunnel connection to the other end (henceforth invalid)
1642 * @param tunnel_ctx place where local state associated
1643 * with the tunnel is stored
1646 tunnel_destruction_handler (void *cls,
1647 const struct GNUNET_MESH_Tunnel *tunnel,
1650 struct ServiceSession * session = tunnel_ctx;
1651 struct ServiceSession * client_session;
1652 struct ServiceSession * curr;
1654 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1656 GNUNET_h2s (&session->key),
1657 GNUNET_i2s (&session->peer));
1658 if (ALICE == session->role) {
1659 // as we have only one peer connected in each session, just remove the session
1661 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1662 session->tunnel = NULL;
1663 // if this happened before we received the answer, we must terminate the session
1664 session->client_notification_task =
1665 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1669 else { //(BOB == session->role) service session
1670 // remove the session, unless it has already been dequeued, but somehow still active
1671 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1672 // scenario: disconnect before alice can send her message to bob.
1673 for (curr = from_service_head; NULL != curr; curr = curr->next)
1674 if (curr == session) {
1675 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1678 // there is a client waiting for this service session, terminate it, too!
1679 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1680 client_session = find_matching_session (from_client_tail,
1682 session->element_count,
1684 free_session (session);
1686 // the client has to check if it was waiting for a result
1687 // or if it was a responder, no point in adding more statefulness
1688 if (client_session && (!do_shutdown)) {
1689 client_session->state = FINALIZED;
1690 client_session->client_notification_task =
1691 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1698 * Compute our scalar product, done by Alice
1700 * @param session - the session associated with this computation
1701 * @param kp - (1) from the protocol definition:
1702 * $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)})$
1703 * @param kq - (2) from the protocol definition:
1704 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1705 * @param s - S from the protocol definition:
1706 * $S := E_A(\sum (r_i + b_i)^2)$
1707 * @param stick - S' from the protocol definition:
1708 * $S' := E_A(\sum r_i^2)$
1709 * @return product as MPI, never NULL
1712 compute_scalar_product (struct ServiceSession * session,
1713 gcry_mpi_t * r, gcry_mpi_t * r_prime, gcry_mpi_t s, gcry_mpi_t s_prime)
1724 count = session->used_element_count;
1725 tmp = gcry_mpi_new (KEYBITS);
1726 // due to the introduced static offset S, we now also have to remove this
1727 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1728 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1729 for (i = 0; i < count; i++) {
1730 decrypt_element (r[i], r[i], my_mu, my_lambda, my_n, my_nsquare);
1731 gcry_mpi_sub (r[i], r[i], my_offset);
1732 gcry_mpi_sub (r[i], r[i], my_offset);
1733 decrypt_element (r_prime[i], r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1734 gcry_mpi_sub (r_prime[i], r_prime[i], my_offset);
1735 gcry_mpi_sub (r_prime[i], r_prime[i], my_offset);
1738 // calculate t = sum(ai)
1739 t = compute_square_sum (session->a, count);
1742 u = gcry_mpi_new (0);
1743 tmp = compute_square_sum (r, count);
1744 gcry_mpi_sub (u, u, tmp);
1745 gcry_mpi_release (tmp);
1748 utick = gcry_mpi_new (0);
1749 tmp = compute_square_sum (r_prime, count);
1750 gcry_mpi_sub (utick, utick, tmp);
1752 GNUNET_assert (p = gcry_mpi_new (0));
1753 GNUNET_assert (ptick = gcry_mpi_new (0));
1756 decrypt_element (s, s, my_mu, my_lambda, my_n, my_nsquare);
1757 decrypt_element (s_prime, s_prime, my_mu, my_lambda, my_n, my_nsquare);
1760 gcry_mpi_add (p, s, t);
1761 gcry_mpi_add (p, p, u);
1764 gcry_mpi_add (ptick, s_prime, t);
1765 gcry_mpi_add (ptick, ptick, utick);
1767 gcry_mpi_release (t);
1768 gcry_mpi_release (u);
1769 gcry_mpi_release (utick);
1772 gcry_mpi_sub (p, p, ptick);
1773 gcry_mpi_release (ptick);
1774 tmp = gcry_mpi_set_ui (tmp, 2);
1775 gcry_mpi_div (p, NULL, p, tmp, 0);
1777 gcry_mpi_release (tmp);
1778 for (i = 0; i < count; i++)
1779 gcry_mpi_release (session->a[i]);
1780 GNUNET_free (session->a);
1787 * prepare the response we will send to alice or bobs' clients.
1788 * in Bobs case the product will be NULL.
1790 * @param session the session associated with our client.
1793 prepare_client_response (void *cls,
1794 const struct GNUNET_SCHEDULER_TaskContext *tc)
1796 struct ServiceSession * session = cls;
1797 struct GNUNET_SCALARPRODUCT_client_response * msg;
1798 unsigned char * product_exported = NULL;
1799 size_t product_length = 0;
1800 uint32_t msg_length = 0;
1805 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1807 if (session->product) {
1808 gcry_mpi_t value = gcry_mpi_new (0);
1810 sign = gcry_mpi_cmp_ui (session->product, 0);
1811 // libgcrypt can not handle a print of a negative number
1812 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1814 gcry_mpi_sub (value, value, session->product);
1816 else if (0 < sign) {
1818 gcry_mpi_add (value, value, session->product);
1823 gcry_mpi_release (session->product);
1824 session->product = NULL;
1826 // get representation as string
1828 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1832 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1834 range = -1; // signal error with product-length = 0 and range = -1
1836 gcry_mpi_release (value);
1839 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1840 msg = GNUNET_malloc (msg_length);
1841 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1842 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1843 if (product_exported != NULL) {
1844 memcpy (&msg[1], product_exported, product_length);
1845 GNUNET_free (product_exported);
1847 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1848 msg->header.size = htons (msg_length);
1850 msg->product_length = htonl (product_length);
1852 session->msg = (struct GNUNET_MessageHeader *) msg;
1853 //transmit this message to our client
1854 session->client_transmit_handle =
1855 GNUNET_SERVER_notify_transmit_ready (session->client,
1857 GNUNET_TIME_UNIT_FOREVER_REL,
1860 if (NULL == session->client_transmit_handle) {
1861 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1862 _ ("Could not send message to client (%p)!\n"),
1864 session->client = NULL;
1865 // callback was not called!
1867 session->msg = NULL;
1870 // gracefully sent message, just terminate session structure
1871 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1872 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1874 GNUNET_h2s (&session->key));
1878 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1880 * @param cls closure (set from #GNUNET_MESH_connect)
1881 * @param tunnel connection to the other end
1882 * @param tunnel_ctx place to store local state associated with the tunnel
1883 * @param sender who sent the message
1884 * @param message the actual message
1885 * @param atsi performance data for the connection
1886 * @return #GNUNET_OK to keep the connection open,
1887 * #GNUNET_SYSERR to close it (signal serious error)
1890 handle_service_request_multipart (void *cls,
1891 struct GNUNET_MESH_Tunnel * tunnel,
1893 const struct GNUNET_MessageHeader * message)
1895 struct ServiceSession * session;
1896 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1897 uint32_t used_elements;
1898 uint32_t contained_elements;
1899 uint32_t msg_length;
1900 unsigned char * current;
1901 struct ServiceSession * responder_session;
1904 // are we in the correct state?
1905 session = (struct ServiceSession *) * tunnel_ctx;
1906 if (BOB != session->role) {
1909 if (WAITING_FOR_MULTIPART_TRANSMISSION != session->state) {
1912 // shorter than minimum?
1913 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1916 used_elements = session->used_element_count;
1917 contained_elements = ntohl (msg->multipart_element_count);
1918 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1919 + contained_elements * PAILLIER_ELEMENT_LENGTH;
1921 if (( ntohs (msg->header.size) != msg_length)
1922 || (used_elements < contained_elements + session->transferred_element_count)) {
1925 current = (unsigned char *) &msg[1];
1926 if (contained_elements != 0) {
1927 gcry_error_t ret = 0;
1928 // Convert each vector element to MPI_value
1929 for (i = session->transferred_element_count; i < session->transferred_element_count+contained_elements; i++) {
1932 ret = gcry_mpi_scan (&session->a[i],
1934 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1935 PAILLIER_ELEMENT_LENGTH,
1938 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1939 i, gcry_strsource (ret), gcry_strerror (ret));
1943 session->transferred_element_count+=contained_elements;
1945 if (session->transferred_element_count == used_elements) {
1946 // single part finished
1947 session->state = SERVICE_REQUEST_RECEIVED;
1948 if (responder_session) {
1949 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1950 if (GNUNET_OK != compute_service_response (session, responder_session)) {
1951 //something went wrong, remove it again...
1952 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1957 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1960 // multipart message
1966 for (i = 0; i < session->transferred_element_count; i++)
1968 gcry_mpi_release (session->a[i]);
1969 gcry_sexp_release (session->remote_pubkey);
1970 session->remote_pubkey = NULL;
1971 GNUNET_free (session->a);
1973 free_session (session);
1974 // and notify our client-session that we could not complete the session
1975 if (session->response)
1976 // we just found the responder session in this queue
1977 session->response->client_notification_task =
1978 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1980 return GNUNET_SYSERR;
1984 * Handle a request from another service to calculate a scalarproduct with us.
1986 * @param cls closure (set from #GNUNET_MESH_connect)
1987 * @param tunnel connection to the other end
1988 * @param tunnel_ctx place to store local state associated with the tunnel
1989 * @param sender who sent the message
1990 * @param message the actual message
1991 * @param atsi performance data for the connection
1992 * @return #GNUNET_OK to keep the connection open,
1993 * #GNUNET_SYSERR to close it (signal serious error)
1996 handle_service_request (void *cls,
1997 struct GNUNET_MESH_Tunnel * tunnel,
1999 const struct GNUNET_MessageHeader * message)
2001 struct ServiceSession * session;
2002 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2003 uint32_t mask_length;
2005 uint32_t used_elements;
2006 uint32_t contained_elements;
2007 uint32_t element_count;
2008 uint32_t msg_length;
2009 unsigned char * current;
2011 enum SessionState needed_state;
2013 session = (struct ServiceSession *) * tunnel_ctx;
2014 if (BOB != session->role) {
2015 GNUNET_break_op (0);
2016 return GNUNET_SYSERR;
2018 // is this tunnel already in use?
2019 if ((session->next) || (from_service_head == session)) {
2020 GNUNET_break_op (0);
2021 return GNUNET_SYSERR;
2023 // Check if message was sent by me, which would be bad!
2024 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2025 GNUNET_free (session);
2027 return GNUNET_SYSERR;
2029 // shorter than expected?
2030 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2031 GNUNET_free (session);
2032 GNUNET_break_op (0);
2033 return GNUNET_SYSERR;
2035 mask_length = ntohl (msg->mask_length);
2036 pk_length = ntohl (msg->pk_length);
2037 used_elements = ntohl (msg->total_element_count);
2038 contained_elements = ntohl (msg->contained_element_count);
2039 element_count = ntohl (msg->element_count);
2040 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2041 +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2043 //sanity check: is the message as long as the message_count fields suggests?
2044 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2045 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2047 GNUNET_free (session);
2048 GNUNET_break_op (0);
2049 return GNUNET_SYSERR;
2051 if (find_matching_session (from_service_tail,
2056 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2057 GNUNET_free (session);
2058 return GNUNET_SYSERR;
2061 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2062 session->element_count = element_count;
2063 session->used_element_count = used_elements;
2064 session->transferred_element_count = contained_elements;
2065 session->tunnel = tunnel;
2068 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2069 current = (unsigned char *) &msg[1];
2070 //preserve the mask, we will need that later on
2071 session->mask = GNUNET_malloc (mask_length);
2072 memcpy (session->mask, current, mask_length);
2074 current += mask_length;
2076 //convert the publickey to sexp
2077 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1)) {
2078 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
2079 GNUNET_free (session->mask);
2080 GNUNET_free (session);
2081 return GNUNET_SYSERR;
2084 current += pk_length;
2086 //check if service queue contains a matching request
2087 needed_state = CLIENT_RESPONSE_RECEIVED;
2088 session->response = find_matching_session (from_client_tail,
2090 session->element_count,
2091 &needed_state, NULL);
2093 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2094 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2095 if (contained_elements != 0) {
2096 gcry_error_t ret = 0;
2097 // Convert each vector element to MPI_value
2098 for (i = 0; i < contained_elements; i++) {
2101 ret = gcry_mpi_scan (&session->a[i],
2103 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2104 PAILLIER_ELEMENT_LENGTH,
2107 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
2108 i, gcry_strsource (ret), gcry_strerror (ret));
2112 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2114 if (contained_elements == used_elements) {
2115 // single part finished
2116 session->state = SERVICE_REQUEST_RECEIVED;
2117 if (session->response) {
2118 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2119 if (GNUNET_OK != compute_service_response (session, session->response)) {
2120 //something went wrong, remove it again...
2121 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2126 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2129 // multipart message
2134 for (i = 0; i < contained_elements; i++)
2136 gcry_mpi_release (session->a[i]);
2137 gcry_sexp_release (session->remote_pubkey);
2138 session->remote_pubkey = NULL;
2139 GNUNET_free (session->a);
2141 free_session (session);
2142 // and notify our client-session that we could not complete the session
2143 if (session->response)
2144 // we just found the responder session in this queue
2145 session->response->client_notification_task =
2146 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2148 return GNUNET_SYSERR;
2152 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2154 * @param cls closure (set from #GNUNET_MESH_connect)
2155 * @param tunnel connection to the other end
2156 * @param tunnel_ctx place to store local state associated with the tunnel
2157 * @param sender who sent the message
2158 * @param message the actual message
2159 * @param atsi performance data for the connection
2160 * @return #GNUNET_OK to keep the connection open,
2161 * #GNUNET_SYSERR to close it (signal serious error)
2164 handle_service_response_multipart (void *cls,
2165 struct GNUNET_MESH_Tunnel * tunnel,
2167 const struct GNUNET_MessageHeader * message)
2169 return GNUNET_SYSERR;
2173 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2175 * @param cls closure (set from #GNUNET_MESH_connect)
2176 * @param tunnel connection to the other end
2177 * @param tunnel_ctx place to store local state associated with the tunnel
2178 * @param sender who sent the message
2179 * @param message the actual message
2180 * @param atsi performance data for the connection
2181 * @return #GNUNET_OK to keep the connection open,
2182 * #GNUNET_SYSERR to close it (we are done)
2185 handle_service_response (void *cls,
2186 struct GNUNET_MESH_Tunnel * tunnel,
2188 const struct GNUNET_MessageHeader * message)
2190 struct ServiceSession * session;
2191 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2192 unsigned char * current;
2193 gcry_mpi_t s = NULL;
2194 gcry_mpi_t s_prime = NULL;
2197 uint32_t contained_element_count;
2199 gcry_mpi_t * r = NULL;
2200 gcry_mpi_t * r_prime = NULL;
2203 GNUNET_assert (NULL != message);
2204 session = (struct ServiceSession *) * tunnel_ctx;
2205 if (ALICE != session->role) {
2206 GNUNET_break_op (0);
2207 return GNUNET_SYSERR;
2210 session->product = NULL;
2211 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2213 //we need at least a peer and one message id to compare
2214 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size)) {
2215 GNUNET_break_op (0);
2218 contained_element_count = ntohl (msg->contained_element_count);
2219 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2220 + 2 * contained_element_count * PAILLIER_ELEMENT_LENGTH
2221 + 2 * PAILLIER_ELEMENT_LENGTH;
2222 //sanity check: is the message as long as the message_count fields suggests?
2223 if ((ntohs (msg->header.size) != msg_size) || (session->used_element_count < contained_element_count)) {
2224 GNUNET_break_op (0);
2227 session->transferred_element_count = contained_element_count;
2229 current = (unsigned char *) &msg[1];
2230 if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current,
2231 PAILLIER_ELEMENT_LENGTH, &read))) {
2232 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2233 GNUNET_break_op (0);
2236 current += PAILLIER_ELEMENT_LENGTH;
2238 if (0 != (rc = gcry_mpi_scan (&s_prime, GCRYMPI_FMT_USG, current,
2239 PAILLIER_ELEMENT_LENGTH, &read))) {
2240 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2241 GNUNET_break_op (0);
2244 current += PAILLIER_ELEMENT_LENGTH;
2245 r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2246 r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2247 // Convert each k[][perm] to its MPI_value
2248 for (i = 0; i < contained_element_count; i++) {
2249 if (0 != (rc = gcry_mpi_scan (&r[i], GCRYMPI_FMT_USG, current,
2250 PAILLIER_ELEMENT_LENGTH, &read))) {
2251 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2252 GNUNET_break_op (0);
2255 current += PAILLIER_ELEMENT_LENGTH;
2256 if (0 != (rc = gcry_mpi_scan (&r_prime[i], GCRYMPI_FMT_USG, current,
2257 PAILLIER_ELEMENT_LENGTH, &read))) {
2258 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2259 GNUNET_break_op (0);
2262 current += PAILLIER_ELEMENT_LENGTH;
2264 if (session->transferred_element_count == session->used_element_count){
2265 session->state = SERVICE_RESPONSE_RECEIVED;
2266 session->product = compute_scalar_product (session, r, r_prime, s, s_prime);
2267 return GNUNET_SYSERR;
2272 gcry_mpi_release (s);
2274 gcry_mpi_release (s_prime);
2275 for (i = 0; r && i < contained_element_count; i++)
2276 if (r[i]) gcry_mpi_release (r[i]);
2277 for (i = 0; r_prime && i < contained_element_count; i++)
2278 if (r_prime[i]) gcry_mpi_release (r_prime[i]);
2279 GNUNET_free_non_null (r);
2280 GNUNET_free_non_null (r_prime);
2282 session->tunnel = NULL;
2283 // send message with product to client
2284 session->client_notification_task =
2285 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2287 // the tunnel has done its job, terminate our connection and the tunnel
2288 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2289 // just close the connection, as recommended by Christian
2290 return GNUNET_SYSERR;
2294 * Task run during shutdown.
2300 shutdown_task (void *cls,
2301 const struct GNUNET_SCHEDULER_TaskContext *tc)
2303 struct ServiceSession * session;
2304 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2306 do_shutdown = GNUNET_YES;
2308 // terminate all owned open tunnels.
2309 for (session = from_client_head; NULL != session; session = session->next) {
2310 if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2311 GNUNET_MESH_tunnel_destroy (session->tunnel);
2312 session->tunnel = NULL;
2314 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2315 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2316 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2318 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2319 GNUNET_SCHEDULER_cancel (session->service_request_task);
2320 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2322 if (NULL != session->client) {
2323 GNUNET_SERVER_client_disconnect (session->client);
2324 session->client = NULL;
2327 for (session = from_service_head; NULL != session; session = session->next)
2328 if (NULL != session->tunnel) {
2329 GNUNET_MESH_tunnel_destroy (session->tunnel);
2330 session->tunnel = NULL;
2334 GNUNET_MESH_disconnect (my_mesh);
2340 * Initialization of the program and message handlers
2342 * @param cls closure
2343 * @param server the initialized server
2344 * @param c configuration to use
2348 struct GNUNET_SERVER_Handle *server,
2349 const struct GNUNET_CONFIGURATION_Handle *c)
2351 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2352 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2353 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2356 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2357 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2358 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2359 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2360 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2363 static const uint32_t ports[] = {
2364 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2367 //generate private/public key set
2368 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2370 // register server callbacks and disconnect handler
2371 GNUNET_SERVER_add_handlers (server, server_handlers);
2372 GNUNET_SERVER_disconnect_notify (server,
2373 &handle_client_disconnect,
2375 GNUNET_break (GNUNET_OK ==
2376 GNUNET_CRYPTO_get_peer_identity (c,
2378 my_mesh = GNUNET_MESH_connect (c, NULL,
2379 &tunnel_incoming_handler,
2380 &tunnel_destruction_handler,
2381 mesh_handlers, ports);
2383 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2384 GNUNET_SCHEDULER_shutdown ();
2387 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2388 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2394 * The main function for the scalarproduct service.
2396 * @param argc number of arguments from the command line
2397 * @param argv command line arguments
2398 * @return 0 ok, 1 on error
2401 main (int argc, char *const *argv)
2403 return (GNUNET_OK ==
2404 GNUNET_SERVICE_run (argc, argv,
2406 GNUNET_SERVICE_OPTION_NONE,
2407 &run, NULL)) ? 0 : 1;
2410 /* end of gnunet-service-ext.c */