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
122 * how many elements actually are used after applying the mask
127 * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
129 uint32_t transferred;
132 * index of the last transferred element for multipart messages
134 uint32_t last_processed;
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;
183 * Bobs matching response session from the client
185 struct ServiceSession * response;
188 * The computed scalar
193 * My transmit handle for the current message to a alice/bob
195 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
198 * My transmit handle for the current message to the client
200 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
203 * tunnel-handle associated with our mesh handle
205 struct GNUNET_MESH_Tunnel * tunnel;
208 * Handle to a task that sends a msg to the our client
210 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
213 * Handle to a task that sends a msg to the our peer
215 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
218 ///////////////////////////////////////////////////////////////////////////////
220 ///////////////////////////////////////////////////////////////////////////////
224 * Handle to the core service (NULL until we've connected to it).
226 static struct GNUNET_MESH_Handle *my_mesh;
229 * The identity of this host.
231 static struct GNUNET_PeerIdentity me;
234 * Service's own public key represented as string
236 static unsigned char * my_pubkey_external;
239 * Service's own public key represented as string
241 static uint32_t my_pubkey_external_length = 0;
246 static gcry_mpi_t my_n;
249 * Service's own n^2 (kept for performance)
251 static gcry_mpi_t my_nsquare;
254 * Service's own public exponent
256 static gcry_mpi_t my_g;
259 * Service's own private multiplier
261 static gcry_mpi_t my_mu;
264 * Service's own private exponent
266 static gcry_mpi_t my_lambda;
269 * Service's offset for values that could possibly be negative but are plaintext for encryption.
271 static gcry_mpi_t my_offset;
274 * Head of our double linked list for client-requests sent to us.
275 * for all of these elements we calculate a scalar product with a remote peer
276 * split between service->service and client->service for simplicity
278 static struct ServiceSession * from_client_head;
280 * Tail of our double linked list for client-requests sent to us.
281 * for all of these elements we calculate a scalar product with a remote peer
282 * split between service->service and client->service for simplicity
284 static struct ServiceSession * from_client_tail;
287 * Head of our double linked list for service-requests sent to us.
288 * for all of these elements we help the requesting service in calculating a scalar product
289 * split between service->service and client->service for simplicity
291 static struct ServiceSession * from_service_head;
294 * Tail of our double linked list for service-requests sent to us.
295 * for all of these elements we help the requesting service in calculating a scalar product
296 * split between service->service and client->service for simplicity
298 static struct ServiceSession * from_service_tail;
301 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
303 static int do_shutdown;
305 ///////////////////////////////////////////////////////////////////////////////
307 ///////////////////////////////////////////////////////////////////////////////
310 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
315 gcry_sexp_t gen_params;
317 gcry_sexp_t tmp_sexp;
326 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
327 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
328 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
331 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
332 gcry_sexp_release (gen_params);
334 // get n and d of our publickey as MPI
335 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
336 GNUNET_assert (tmp_sexp);
337 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
338 gcry_sexp_release (tmp_sexp);
339 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
340 GNUNET_assert (tmp_sexp);
341 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
342 gcry_sexp_release (tmp_sexp);
343 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
344 GNUNET_assert (tmp_sexp);
345 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
346 gcry_sexp_release (key);
348 tmp1 = gcry_mpi_new (0);
349 tmp2 = gcry_mpi_new (0);
350 gcd = gcry_mpi_new (0);
351 my_g = gcry_mpi_new (0);
352 my_mu = gcry_mpi_new (0);
353 my_nsquare = gcry_mpi_new (0);
354 my_lambda = gcry_mpi_new (0);
357 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
358 gcry_mpi_sub_ui (tmp1, p, 1);
359 gcry_mpi_sub_ui (tmp2, q, 1);
360 gcry_mpi_gcd (gcd, tmp1, tmp2);
361 gcry_mpi_set (my_lambda, tmp1);
362 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
363 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
366 gcry_mpi_mul (my_nsquare, my_n, my_n);
370 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
371 // g must be smaller than n^2
372 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
375 // g must have gcd == 1 with n^2
376 gcry_mpi_gcd (gcd, my_g, my_nsquare);
378 while (gcry_mpi_cmp_ui (gcd, 1));
380 // is this a valid g?
381 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
382 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
383 gcry_mpi_sub_ui (tmp1, tmp1, 1);
384 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
385 gcry_mpi_gcd (gcd, tmp1, my_n);
387 while (gcry_mpi_cmp_ui (gcd, 1));
389 // calculate our mu based on g and n.
390 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
391 gcry_mpi_invm (my_mu, tmp1, my_n);
393 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
394 "(public-key (paillier (n %M)(g %M)))",
397 // get the length of this sexpression
398 my_pubkey_external_length = gcry_sexp_sprint (key,
403 GNUNET_assert (my_pubkey_external_length > 0);
404 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
406 // convert the sexpression to canonical format
407 gcry_sexp_sprint (key,
410 my_pubkey_external_length);
412 gcry_sexp_release (key);
414 // offset has to be sufficiently small to allow computation of:
415 // m1+m2 mod n == (S + a) + (S + b) mod n,
416 // if we have more complex operations, this factor needs to be lowered
417 my_offset = gcry_mpi_new (KEYBITS / 3);
418 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
424 * If target != size, move target bytes to the
425 * end of the size-sized buffer and zero out the
426 * first target-size bytes.
428 * @param buf original buffer
429 * @param size number of bytes in the buffer
430 * @param target target size of the buffer
433 adjust (unsigned char *buf, size_t size, size_t target)
436 memmove (&buf[target - size], buf, size);
437 memset (buf, 0, target - size);
442 * encrypts an element using the paillier crypto system
444 * @param c ciphertext (output)
446 * @param g the public base
447 * @param n the module from which which r is chosen (Z*_n)
448 * @param n_square the module for encryption, for performance reasons.
451 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
455 GNUNET_assert (tmp = gcry_mpi_new (0));
457 while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
458 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
459 // r must be 1 < r < n
462 gcry_mpi_powm (c, g, m, n_square);
463 gcry_mpi_powm (tmp, tmp, n, n_square);
464 gcry_mpi_mulm (c, tmp, c, n_square);
466 gcry_mpi_release (tmp);
470 * decrypts an element using the paillier crypto system
472 * @param m plaintext (output)
473 * @param c the ciphertext
474 * @param mu the modifier to correct encryption
475 * @param lambda the private exponent
476 * @param n the outer module for decryption
477 * @param n_square the inner module for decryption
480 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)
482 gcry_mpi_powm (m, c, lambda, n_square);
483 gcry_mpi_sub_ui (m, m, 1);
484 gcry_mpi_div (m, NULL, m, n, 0);
485 gcry_mpi_mulm (m, m, mu, n);
489 * computes the square sum over a vector of a given length.
491 * @param vector the vector to encrypt
492 * @param length the length of the vector
493 * @return an MPI value containing the calculated sum, never NULL
496 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
502 GNUNET_assert (sum = gcry_mpi_new (0));
503 GNUNET_assert (elem = gcry_mpi_new (0));
505 // calculare E(sum (ai ^ 2), publickey)
506 for (i = 0; i < length; i++) {
507 gcry_mpi_mul (elem, vector[i], vector[i]);
508 gcry_mpi_add (sum, sum, elem);
510 gcry_mpi_release (elem);
517 prepare_service_request_multipart (void *cls,
518 const struct GNUNET_SCHEDULER_TaskContext *tc);
520 prepare_service_response_multipart (void *cls,
521 const struct GNUNET_SCHEDULER_TaskContext *tc);
525 * Primitive callback for copying over a message, as they
526 * usually are too complex to be handled in the callback itself.
527 * clears a session-callback, if a session was handed over and the transmit handle was stored
529 * @param cls the message object
530 * @param size the size of the buffer we got
531 * @param buf the buffer to copy the message to
532 * @return 0 if we couldn't copy, else the size copied over
535 do_send_message (void *cls, size_t size, void *buf)
537 struct ServiceSession * session = cls;
542 if (ntohs (session->msg->size) != size)
548 type = ntohs (session->msg->type);
549 memcpy (buf, session->msg, size);
550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551 "Sent a message of type %hu.\n",
553 GNUNET_free (session->msg);
558 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
559 session->state = FINALIZED;
560 session->client_transmit_handle = NULL;
562 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
563 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
565 session->service_transmit_handle = NULL;
566 // reset flags for sending
567 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used != session->transferred))
568 prepare_service_request_multipart (session, NULL);
569 //TODO we have sent a message and now need to trigger trigger the next multipart message sending
571 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
572 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
574 session->service_transmit_handle = NULL;
575 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used != session->transferred))
576 prepare_service_response_multipart (session, NULL);
579 session->service_transmit_handle = NULL;
586 * initializes a new vector with fresh MPI values (=0) of a given length
588 * @param length of the vector to create
589 * @return the initialized vector, never NULL
592 initialize_mpi_vector (uint32_t length)
595 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
597 for (i = 0; i < length; i++)
598 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
603 * permutes an MPI vector according to the given permutation vector
605 * @param vector the vector to permuted
606 * @param perm the permutation to use
607 * @param length the length of the vectors
608 * @return the permuted vector (same as input), never NULL
611 permute_vector (gcry_mpi_t * vector,
615 gcry_mpi_t tmp[length];
618 GNUNET_assert (length > 0);
621 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
623 // permute vector according to given
624 for (i = 0; i < length; i++)
625 vector[i] = tmp[perm[i]];
631 * Populate a vector with random integer values and convert them to
633 * @param length the length of the vector we must generate
634 * @return an array of MPI values with random values
637 generate_random_vector (uint32_t length)
639 gcry_mpi_t * random_vector;
643 random_vector = initialize_mpi_vector (length);
644 for (i = 0; i < length; i++) {
645 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
647 // long to gcry_mpi_t
649 gcry_mpi_sub_ui (random_vector[i],
653 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
656 return random_vector;
660 * Finds a not terminated client/service session in the
661 * given DLL based on session key, element count and state.
663 * @param tail - the tail of the DLL
664 * @param my - the session to compare it to
665 * @return a pointer to a matching session,
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 free_session_variables (struct ServiceSession * session)
701 for (i = 0; i < session->used; i++)
702 if (session->a[i]) gcry_mpi_release (session->a[i]);
703 GNUNET_free (session->a);
705 GNUNET_free_non_null (session->mask);
707 for (i = 0; i < session->used; i++)
708 if (session->r[i]) gcry_mpi_release (session->r[i]);
709 GNUNET_free(session->r);
711 if (session->r_prime){
712 for (i = 0; i < session->used; i++)
713 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
714 GNUNET_free(session->r_prime);
717 gcry_mpi_release (session->s);
718 if (session->s_prime)
719 gcry_mpi_release (session->s_prime);
720 if (session->product)
721 gcry_mpi_release (session->product);
723 if (session->remote_pubkey)
724 gcry_sexp_release (session->remote_pubkey);
726 GNUNET_free_non_null (session->vector);
728 ///////////////////////////////////////////////////////////////////////////////
729 // Event and Message Handlers
730 ///////////////////////////////////////////////////////////////////////////////
733 * A client disconnected.
735 * Remove the associated session(s), release datastructures
736 * and cancel pending outgoing transmissions to the client.
737 * if the session has not yet completed, we also cancel Alice's request to Bob.
739 * @param cls closure, NULL
740 * @param client identification of the client
743 handle_client_disconnect (void *cls,
744 struct GNUNET_SERVER_Client *client)
746 struct ServiceSession *session;
750 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
754 _ ("Client (%p) disconnected from us.\n"), client);
755 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
757 if (!(session->role == BOB && session->state == FINALIZED)) {
758 //we MUST terminate any client message underway
759 if (session->service_transmit_handle && session->tunnel)
760 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
761 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
762 GNUNET_MESH_tunnel_destroy (session->tunnel);
764 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
765 GNUNET_SCHEDULER_cancel (session->client_notification_task);
766 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
768 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
769 GNUNET_SCHEDULER_cancel (session->service_request_task);
770 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
772 if (NULL != session->client_transmit_handle) {
773 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
774 session->client_transmit_handle = NULL;
776 free_session_variables (session);
777 GNUNET_free (session);
781 * Notify the client that the session has succeeded or failed completely.
782 * This message gets sent to
783 * * alice's client if bob disconnected or to
784 * * bob's client if the operation completed or alice disconnected
786 * @param client_session the associated client session
787 * @return GNUNET_NO, if we could not notify the client
788 * GNUNET_YES if we notified it.
791 prepare_client_end_notification (void * cls,
792 const struct GNUNET_SCHEDULER_TaskContext * tc)
794 struct ServiceSession * session = cls;
795 struct GNUNET_SCALARPRODUCT_client_response * msg;
797 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
799 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
800 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
801 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
802 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
803 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
804 // signal error if not signalized, positive result-range field but zero length.
805 msg->product_length = htonl (0);
806 msg->range = (session->state == FINALIZED) ? 0 : -1;
808 session->msg = &msg->header;
810 //transmit this message to our client
811 session->client_transmit_handle =
812 GNUNET_SERVER_notify_transmit_ready (session->client,
813 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
814 GNUNET_TIME_UNIT_FOREVER_REL,
818 // if we could not even queue our request, something is wrong
819 if (NULL == session->client_transmit_handle) {
820 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
821 // usually gets freed by do_send_message
826 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
831 prepare_service_response_multipart (void *cls,
832 const struct GNUNET_SCHEDULER_TaskContext *tc)
834 struct ServiceSession * session = cls;
835 unsigned char * current;
836 unsigned char * element_exported;
837 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
841 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
843 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
844 todo_count = session->used - session->transferred;
846 if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
847 // send the currently possible maximum chunk, we always transfer both permutations
848 todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
850 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
851 msg = GNUNET_malloc (msg_length);
852 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
853 msg->header.size = htons (msg_length);
854 msg->multipart_element_count = htonl (todo_count);
856 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
857 current = (unsigned char *) &msg[1];
859 for (i = session->transferred; i < session->transferred + todo_count; i++) {
861 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
862 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
863 element_exported, PAILLIER_ELEMENT_LENGTH,
866 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
867 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
868 current += PAILLIER_ELEMENT_LENGTH;
870 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
871 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
872 element_exported, PAILLIER_ELEMENT_LENGTH,
874 session->r_prime[i]));
875 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
876 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
877 current += PAILLIER_ELEMENT_LENGTH;
879 GNUNET_free (element_exported);
880 for (i = session->transferred; i < session->transferred; i++) {
881 gcry_mpi_release (session->r_prime[i]);
882 gcry_mpi_release (session->r[i]);
884 session->transferred += todo_count;
885 session->msg = (struct GNUNET_MessageHeader *) msg;
886 session->service_transmit_handle =
887 GNUNET_MESH_notify_transmit_ready (session->tunnel,
889 GNUNET_TIME_UNIT_FOREVER_REL,
893 //disconnect our client
894 if (NULL == session->service_transmit_handle) {
895 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
896 session->state = FINALIZED;
898 session->response->client_notification_task =
899 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
903 if (session->transferred != session->used)
905 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
908 session->state = FINALIZED;
913 * generates the response message to be sent to alice after computing
914 * the values (1), (2), S and S'
915 * (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)})$
916 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
917 * S: $S := E_A(sum (r_i + b_i)^2)$
918 * S': $S' := E_A(sum r_i^2)$
920 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
921 * @param s_prime S': $S' := E_A(sum r_i^2)$
922 * @param session the associated requesting session with alice
923 * @return GNUNET_NO if we could not send our message
924 * GNUNET_OK if the operation succeeded
927 prepare_service_response (gcry_mpi_t s,
929 struct ServiceSession * session)
931 struct GNUNET_SCALARPRODUCT_service_response * msg;
932 uint32_t msg_length = 0;
933 unsigned char * current = NULL;
934 unsigned char * element_exported = NULL;
935 size_t element_length = 0;
938 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
939 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
941 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used * PAILLIER_ELEMENT_LENGTH) { //kp, kq
942 msg_length += +2 * session->used * PAILLIER_ELEMENT_LENGTH;
943 session->transferred = session->used;
946 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
949 msg = GNUNET_malloc (msg_length);
951 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
952 msg->header.size = htons (msg_length);
953 msg->total_element_count = htonl (session->total);
954 msg->contained_element_count = htonl (session->used);
955 msg->contained_element_count = htonl (session->transferred);
956 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
957 current = (unsigned char *) &msg[1];
959 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
960 // 4 times the same logics with slight variations.
961 // doesn't really justify having 2 functions for that
962 // so i put it into blocks to enhance readability
964 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
965 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
966 element_exported, PAILLIER_ELEMENT_LENGTH,
969 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
970 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
971 current += PAILLIER_ELEMENT_LENGTH;
974 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
975 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
976 element_exported, PAILLIER_ELEMENT_LENGTH,
979 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
980 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
981 current += PAILLIER_ELEMENT_LENGTH;
984 for (i = 0; i < session->transferred; i++) {
986 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
987 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
988 element_exported, PAILLIER_ELEMENT_LENGTH,
991 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
992 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
993 current += PAILLIER_ELEMENT_LENGTH;
995 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
996 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
997 element_exported, PAILLIER_ELEMENT_LENGTH,
999 session->r_prime[i]));
1000 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1001 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1002 current += PAILLIER_ELEMENT_LENGTH;
1005 GNUNET_free (element_exported);
1006 for (i = 0; i < session->transferred; i++) {
1007 gcry_mpi_release (session->r_prime[i]);
1008 gcry_mpi_release (session->r[i]);
1010 gcry_mpi_release (s);
1011 gcry_mpi_release (s_prime);
1013 session->msg = (struct GNUNET_MessageHeader *) msg;
1014 session->service_transmit_handle =
1015 GNUNET_MESH_notify_transmit_ready (session->tunnel,
1017 GNUNET_TIME_UNIT_FOREVER_REL,
1021 //disconnect our client
1022 if (NULL == session->service_transmit_handle) {
1023 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1024 session->state = FINALIZED;
1026 session->response->client_notification_task =
1027 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1031 if (session->transferred != session->used)
1033 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1036 session->state = FINALIZED;
1043 * compute the values
1044 * (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)})$
1045 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1046 * S: $S := E_A(\sum (r_i + b_i)^2)$
1047 * S': $S' := E_A(\sum r_i^2)$
1049 * @param request the requesting session + bob's requesting peer
1050 * @param response the responding session + bob's client handle
1051 * @return GNUNET_SYSERR if the computation failed
1052 * GNUNET_OK if everything went well.
1055 compute_service_response (struct ServiceSession * request,
1056 struct ServiceSession * response)
1060 int ret = GNUNET_SYSERR;
1064 gcry_mpi_t * rand = NULL;
1065 gcry_mpi_t * r = NULL;
1066 gcry_mpi_t * r_prime = NULL;
1069 gcry_mpi_t * a_pi_prime;
1071 gcry_mpi_t * rand_pi;
1072 gcry_mpi_t * rand_pi_prime;
1073 gcry_mpi_t s = NULL;
1074 gcry_mpi_t s_prime = NULL;
1075 gcry_mpi_t remote_n = NULL;
1076 gcry_mpi_t remote_nsquare;
1077 gcry_mpi_t remote_g = NULL;
1078 gcry_sexp_t tmp_exp;
1081 count = request->used;
1083 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1084 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1085 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1086 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1087 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1088 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1090 // convert responder session to from long to mpi
1091 for (i = 0, j = 0; i < response->total && j < count; i++) {
1092 if (request->mask[i / 8] & (1 << (i % 8))) {
1093 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1094 // long to gcry_mpi_t
1095 if (0 > response->vector[i]) {
1096 b[j] = gcry_mpi_new (0);
1097 gcry_mpi_sub_ui (b[j], b[j], value);
1100 b[j] = gcry_mpi_set_ui (NULL, value);
1105 GNUNET_free (response->vector);
1106 response->vector = NULL;
1108 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1110 GNUNET_break_op (0);
1111 gcry_sexp_release (request->remote_pubkey);
1112 request->remote_pubkey = NULL;
1115 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1118 gcry_sexp_release (tmp_exp);
1121 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1122 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1123 gcry_sexp_release (tmp_exp);
1124 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1125 gcry_sexp_release (request->remote_pubkey);
1126 request->remote_pubkey = NULL;
1128 GNUNET_break_op (0);
1129 gcry_mpi_release (remote_n);
1132 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1135 gcry_mpi_release (remote_n);
1136 gcry_sexp_release (tmp_exp);
1139 gcry_sexp_release (tmp_exp);
1141 // generate r, p and q
1142 rand = generate_random_vector (count);
1143 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1144 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1145 //initialize the result vectors
1146 r = initialize_mpi_vector (count);
1147 r_prime = initialize_mpi_vector (count);
1149 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1150 // those values, thus we can work with the references
1151 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1152 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1153 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1154 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1155 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1157 // generate p and q permutations for a, b and r
1158 GNUNET_assert (permute_vector (a_pi, p, count));
1159 GNUNET_assert (permute_vector (b_pi, p, count));
1160 GNUNET_assert (permute_vector (rand_pi, p, count));
1161 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1162 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1164 // encrypt the element
1165 // for the sake of readability I decided to have dedicated permutation
1166 // vectors, which get rid of all the lookups in p/q.
1167 // however, ap/aq are not absolutely necessary but are just abstraction
1168 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1169 for (i = 0; i < count; i++) {
1170 // E(S - r_pi - b_pi)
1171 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1172 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1173 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1175 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1176 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1180 GNUNET_free (rand_pi);
1182 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1183 for (i = 0; i < count; i++) {
1185 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1186 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1188 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1189 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1191 GNUNET_free (a_pi_prime);
1192 GNUNET_free (rand_pi_prime);
1195 request->r_prime = r_prime;
1196 request->response = response;
1198 // Calculate S' = E(SUM( r_i^2 ))
1199 s_prime = compute_square_sum (rand, count);
1200 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1202 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1203 for (i = 0; i < count; i++) {
1204 gcry_mpi_add (rand[i], rand[i], b[i]);
1206 s = compute_square_sum (rand, count);
1207 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1208 gcry_mpi_release (remote_n);
1209 gcry_mpi_release (remote_g);
1210 gcry_mpi_release (remote_nsquare);
1212 // release r and tmp
1213 for (i = 0; i < count; i++)
1214 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1215 gcry_mpi_release (rand[i]);
1217 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1218 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1219 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1220 GNUNET_i2s (&request->peer));
1225 for (i = 0; i < count; i++) {
1226 gcry_mpi_release (b[i]);
1227 gcry_mpi_release (request->a[i]);
1231 GNUNET_free (request->a);
1238 prepare_service_request_multipart (void *cls,
1239 const struct GNUNET_SCHEDULER_TaskContext *tc)
1241 struct ServiceSession * session = cls;
1242 unsigned char * current;
1243 unsigned char * element_exported;
1244 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1247 uint32_t msg_length;
1248 uint32_t todo_count;
1249 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1253 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1254 todo_count = session->used - session->transferred;
1256 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1257 // send the currently possible maximum chunk
1258 todo_count = MULTIPART_ELEMENT_CAPACITY;
1260 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1261 msg = GNUNET_malloc (msg_length);
1262 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1263 msg->header.size = htons (msg_length);
1264 msg->multipart_element_count = htonl (todo_count);
1266 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1267 a = gcry_mpi_new (KEYBITS * 2);
1268 current = (unsigned char *) &msg[1];
1269 // encrypt our vector and generate string representations
1270 for (i = session->last_processed, j = 0; i < session->total; i++) {
1271 // is this a used element?
1272 if (session->mask[i / 8] & 1 << (i % 8)) {
1273 if (todo_count <= j)
1274 break; //reached end of this message, can't include more
1276 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1277 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1279 a = gcry_mpi_set_ui (a, 0);
1280 // long to gcry_mpi_t
1281 if (session->vector[i] < 0)
1282 gcry_mpi_sub_ui (a, a, value);
1284 gcry_mpi_add_ui (a, a, value);
1286 session->a[session->transferred + j++] = gcry_mpi_set (NULL, a);
1287 gcry_mpi_add (a, a, my_offset);
1288 encrypt_element (a, a, my_g, my_n, my_nsquare);
1290 // get representation as string
1291 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1292 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1293 element_exported, PAILLIER_ELEMENT_LENGTH,
1297 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1298 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1300 // copy over to the message
1301 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1302 current += PAILLIER_ELEMENT_LENGTH;
1305 gcry_mpi_release (a);
1306 GNUNET_free (element_exported);
1307 session->transferred += todo_count;
1309 session->msg = (struct GNUNET_MessageHeader *) msg;
1310 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1312 //transmit via mesh messaging
1313 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1314 GNUNET_TIME_UNIT_FOREVER_REL,
1318 if (!session->service_transmit_handle) {
1319 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1321 session->msg = NULL;
1322 session->client_notification_task =
1323 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1327 if (session->transferred != session->used) {
1328 session->last_processed = i;
1332 session->state = WAITING_FOR_SERVICE_RESPONSE;
1336 * Executed by Alice, fills in a service-request message and sends it to the given peer
1338 * @param session the session associated with this request, then also holds the CORE-handle
1339 * @return #GNUNET_SYSERR if we could not send the message
1340 * #GNUNET_NO if the message was too large
1341 * #GNUNET_OK if we sent it
1344 prepare_service_request (void *cls,
1345 const struct GNUNET_SCHEDULER_TaskContext *tc)
1347 struct ServiceSession * session = cls;
1348 unsigned char * current;
1349 unsigned char * element_exported;
1350 struct GNUNET_SCALARPRODUCT_service_request * msg;
1353 uint32_t msg_length;
1354 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1358 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1360 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1362 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1363 +session->mask_length
1364 + my_pubkey_external_length;
1366 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used * PAILLIER_ELEMENT_LENGTH) {
1367 msg_length += session->used * PAILLIER_ELEMENT_LENGTH;
1368 session->transferred = session->used;
1371 //create a multipart msg, first we calculate a new msg size for the head msg
1372 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1375 msg = GNUNET_malloc (msg_length);
1376 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1377 msg->total_element_count = htonl (session->used);
1378 msg->contained_element_count = htonl (session->transferred);
1379 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1380 msg->mask_length = htonl (session->mask_length);
1381 msg->pk_length = htonl (my_pubkey_external_length);
1382 msg->element_count = htonl (session->total);
1383 msg->header.size = htons (msg_length);
1385 // fill in the payload
1386 current = (unsigned char *) &msg[1];
1387 // copy over the mask
1388 memcpy (current, session->mask, session->mask_length);
1389 // copy over our public key
1390 current += session->mask_length;
1391 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1392 current += my_pubkey_external_length;
1394 // now copy over the element vector
1395 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1396 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
1397 a = gcry_mpi_new (KEYBITS * 2);
1398 // encrypt our vector and generate string representations
1399 for (i = 0, j = 0; i < session->total; i++) {
1400 // if this is a used element...
1401 if (session->mask[i / 8] & 1 << (i % 8)) {
1402 if (session->transferred <= j)
1403 break; //reached end of this message, can't include more
1405 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1406 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1408 a = gcry_mpi_set_ui (a, 0);
1409 // long to gcry_mpi_t
1410 if (session->vector[i] < 0)
1411 gcry_mpi_sub_ui (a, a, value);
1413 gcry_mpi_add_ui (a, a, value);
1415 session->a[j++] = gcry_mpi_set (NULL, a);
1416 gcry_mpi_add (a, a, my_offset);
1417 encrypt_element (a, a, my_g, my_n, my_nsquare);
1419 // get representation as string
1420 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1421 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1422 element_exported, PAILLIER_ELEMENT_LENGTH,
1426 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1427 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1429 // copy over to the message
1430 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1431 current += PAILLIER_ELEMENT_LENGTH;
1434 gcry_mpi_release (a);
1435 GNUNET_free (element_exported);
1437 session->msg = (struct GNUNET_MessageHeader *) msg;
1438 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1440 //transmit via mesh messaging
1441 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1442 GNUNET_TIME_UNIT_FOREVER_REL,
1446 if (!session->service_transmit_handle) {
1447 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1449 session->msg = NULL;
1450 session->client_notification_task =
1451 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1455 if (session->transferred != session->used) {
1456 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1457 session->last_processed = i;
1460 //singlepart message
1461 session->state = WAITING_FOR_SERVICE_RESPONSE;
1465 * Handler for a client request message.
1466 * Can either be type A or B
1467 * A: request-initiation to compute a scalar product with a peer
1468 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1470 * @param cls closure
1471 * @param client identification of the client
1472 * @param message the actual message
1475 handle_client_request (void *cls,
1476 struct GNUNET_SERVER_Client *client,
1477 const struct GNUNET_MessageHeader *message)
1479 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1480 struct ServiceSession * session;
1481 uint32_t element_count;
1482 uint32_t mask_length;
1487 // only one concurrent session per client connection allowed, simplifies logics a lot...
1488 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1489 if ((NULL != session) && (session->state != FINALIZED)) {
1490 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1493 else if (NULL != session) {
1494 // old session is already completed, clean it up
1495 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1496 free_session_variables (session);
1497 GNUNET_free (session);
1500 //we need at least a peer and one message id to compare
1501 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1502 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1503 _ ("Too short message received from client!\n"));
1504 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1508 msg_type = ntohs (msg->header.type);
1509 element_count = ntohl (msg->element_count);
1510 mask_length = ntohl (msg->mask_length);
1512 //sanity check: is the message as long as the message_count fields suggests?
1513 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1514 || (0 == element_count)) {
1515 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1516 _ ("Invalid message received from client, session information incorrect!\n"));
1517 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1521 // do we have a duplicate session here already?
1522 if (NULL != find_matching_session (from_client_tail,
1526 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1527 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1528 GNUNET_h2s (&msg->key));
1529 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1533 session = GNUNET_new (struct ServiceSession);
1534 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1535 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1536 session->client = client;
1537 session->total = element_count;
1538 session->mask_length = mask_length;
1539 // get our transaction key
1540 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1541 //allocate memory for vector and encrypted vector
1542 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1543 vector = (int32_t *) & msg[1];
1545 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1548 GNUNET_h2s (&session->key));
1550 session->role = ALICE;
1552 session->mask = GNUNET_malloc (mask_length);
1553 memcpy (session->mask, &vector[element_count], mask_length);
1555 // copy over the elements
1557 for (i = 0; i < element_count; i++) {
1558 session->vector[i] = ntohl (vector[i]);
1559 if (session->vector[i] == 0)
1560 session->mask[i / 8] &= ~(1 << (i % 8));
1561 if (session->mask[i / 8] & (1 << (i % 8)))
1565 if (0 == session->used) {
1566 GNUNET_break_op (0);
1567 GNUNET_free (session->vector);
1568 GNUNET_free (session);
1569 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1572 //session with ourself makes no sense!
1573 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1575 GNUNET_free (session->vector);
1576 GNUNET_free (session);
1577 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1581 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1582 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1583 _ ("Creating new tunnel to for session with key %s.\n"),
1584 GNUNET_h2s (&session->key));
1585 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1587 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1590 //prepare_service_request, tunnel_peer_disconnect_handler,
1591 if (!session->tunnel) {
1593 GNUNET_free (session->vector);
1594 GNUNET_free (session);
1595 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1598 GNUNET_SERVER_client_set_user_context (client, session);
1599 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1601 session->state = CLIENT_REQUEST_RECEIVED;
1602 session->service_request_task =
1603 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1608 struct ServiceSession * requesting_session;
1609 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1611 session->role = BOB;
1612 session->mask = NULL;
1613 // copy over the elements
1614 session->used = element_count;
1615 for (i = 0; i < element_count; i++)
1616 session->vector[i] = ntohl (vector[i]);
1617 session->state = CLIENT_RESPONSE_RECEIVED;
1619 GNUNET_SERVER_client_set_user_context (client, session);
1620 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1622 //check if service queue contains a matching request
1623 requesting_session = find_matching_session (from_service_tail,
1626 &needed_state, NULL);
1627 if (NULL != requesting_session) {
1628 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));
1629 if (GNUNET_OK != compute_service_response (requesting_session, session))
1630 session->client_notification_task =
1631 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1636 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));
1637 // no matching session exists yet, store the response
1638 // for later processing by handle_service_request()
1641 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1645 * Function called for inbound tunnels.
1647 * @param cls closure
1648 * @param tunnel new handle to the tunnel
1649 * @param initiator peer that started the tunnel
1650 * @param atsi performance information for the tunnel
1651 * @return initial tunnel context for the tunnel
1652 * (can be NULL -- that's not an error)
1655 tunnel_incoming_handler (void *cls,
1656 struct GNUNET_MESH_Tunnel *tunnel,
1657 const struct GNUNET_PeerIdentity *initiator,
1660 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1662 c->peer = *initiator;
1665 c->state = WAITING_FOR_SERVICE_REQUEST;
1670 * Function called whenever a tunnel is destroyed. Should clean up
1671 * any associated state.
1673 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1675 * @param cls closure (set from GNUNET_MESH_connect)
1676 * @param tunnel connection to the other end (henceforth invalid)
1677 * @param tunnel_ctx place where local state associated
1678 * with the tunnel is stored
1681 tunnel_destruction_handler (void *cls,
1682 const struct GNUNET_MESH_Tunnel *tunnel,
1685 struct ServiceSession * session = tunnel_ctx;
1686 struct ServiceSession * client_session;
1687 struct ServiceSession * curr;
1689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1691 GNUNET_h2s (&session->key),
1692 GNUNET_i2s (&session->peer));
1693 if (ALICE == session->role) {
1694 // as we have only one peer connected in each session, just remove the session
1696 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1697 session->tunnel = NULL;
1698 // if this happened before we received the answer, we must terminate the session
1699 session->client_notification_task =
1700 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1704 else { //(BOB == session->role) service session
1705 // remove the session, unless it has already been dequeued, but somehow still active
1706 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1707 // scenario: disconnect before alice can send her message to bob.
1708 for (curr = from_service_head; NULL != curr; curr = curr->next)
1709 if (curr == session) {
1710 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1713 // there is a client waiting for this service session, terminate it, too!
1714 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1715 client_session = find_matching_session (from_client_tail,
1719 free_session_variables (session);
1720 GNUNET_free (session);
1722 // the client has to check if it was waiting for a result
1723 // or if it was a responder, no point in adding more statefulness
1724 if (client_session && (!do_shutdown)) {
1725 client_session->state = FINALIZED;
1726 client_session->client_notification_task =
1727 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1734 * Compute our scalar product, done by Alice
1736 * @param session - the session associated with this computation
1737 * @param kp - (1) from the protocol definition:
1738 * $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)})$
1739 * @param kq - (2) from the protocol definition:
1740 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1741 * @param s - S from the protocol definition:
1742 * $S := E_A(\sum (r_i + b_i)^2)$
1743 * @param stick - S' from the protocol definition:
1744 * $S' := E_A(\sum r_i^2)$
1745 * @return product as MPI, never NULL
1748 compute_scalar_product (struct ServiceSession * session)
1759 count = session->used;
1760 tmp = gcry_mpi_new (KEYBITS);
1761 // due to the introduced static offset S, we now also have to remove this
1762 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1763 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1764 for (i = 0; i < count; i++) {
1765 decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1766 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1767 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1768 decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1769 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1770 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1773 // calculate t = sum(ai)
1774 t = compute_square_sum (session->a, count);
1777 u = gcry_mpi_new (0);
1778 tmp = compute_square_sum (session->r, count);
1779 gcry_mpi_sub (u, u, tmp);
1780 gcry_mpi_release (tmp);
1783 utick = gcry_mpi_new (0);
1784 tmp = compute_square_sum (session->r_prime, count);
1785 gcry_mpi_sub (utick, utick, tmp);
1787 GNUNET_assert (p = gcry_mpi_new (0));
1788 GNUNET_assert (ptick = gcry_mpi_new (0));
1791 decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1792 decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1795 gcry_mpi_add (p, session->s, t);
1796 gcry_mpi_add (p, p, u);
1799 gcry_mpi_add (ptick, session->s_prime, t);
1800 gcry_mpi_add (ptick, ptick, utick);
1802 gcry_mpi_release (t);
1803 gcry_mpi_release (u);
1804 gcry_mpi_release (utick);
1807 gcry_mpi_sub (p, p, ptick);
1808 gcry_mpi_release (ptick);
1809 tmp = gcry_mpi_set_ui (tmp, 2);
1810 gcry_mpi_div (p, NULL, p, tmp, 0);
1812 gcry_mpi_release (tmp);
1813 for (i = 0; i < count; i++)
1814 gcry_mpi_release (session->a[i]);
1815 GNUNET_free (session->a);
1822 * prepare the response we will send to alice or bobs' clients.
1823 * in Bobs case the product will be NULL.
1825 * @param session the session associated with our client.
1828 prepare_client_response (void *cls,
1829 const struct GNUNET_SCHEDULER_TaskContext *tc)
1831 struct ServiceSession * session = cls;
1832 struct GNUNET_SCALARPRODUCT_client_response * msg;
1833 unsigned char * product_exported = NULL;
1834 size_t product_length = 0;
1835 uint32_t msg_length = 0;
1840 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1842 if (session->product) {
1843 gcry_mpi_t value = gcry_mpi_new (0);
1845 sign = gcry_mpi_cmp_ui (session->product, 0);
1846 // libgcrypt can not handle a print of a negative number
1847 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1849 gcry_mpi_sub (value, value, session->product);
1851 else if (0 < sign) {
1853 gcry_mpi_add (value, value, session->product);
1858 gcry_mpi_release (session->product);
1859 session->product = NULL;
1861 // get representation as string
1863 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1867 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1869 range = -1; // signal error with product-length = 0 and range = -1
1871 gcry_mpi_release (value);
1874 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1875 msg = GNUNET_malloc (msg_length);
1876 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1877 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1878 if (product_exported != NULL) {
1879 memcpy (&msg[1], product_exported, product_length);
1880 GNUNET_free (product_exported);
1882 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1883 msg->header.size = htons (msg_length);
1885 msg->product_length = htonl (product_length);
1887 session->msg = (struct GNUNET_MessageHeader *) msg;
1888 //transmit this message to our client
1889 session->client_transmit_handle =
1890 GNUNET_SERVER_notify_transmit_ready (session->client,
1892 GNUNET_TIME_UNIT_FOREVER_REL,
1895 if (NULL == session->client_transmit_handle) {
1896 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1897 _ ("Could not send message to client (%p)!\n"),
1899 session->client = NULL;
1900 // callback was not called!
1902 session->msg = NULL;
1905 // gracefully sent message, just terminate session structure
1906 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1907 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1909 GNUNET_h2s (&session->key));
1913 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1915 * @param cls closure (set from #GNUNET_MESH_connect)
1916 * @param tunnel connection to the other end
1917 * @param tunnel_ctx place to store local state associated with the tunnel
1918 * @param sender who sent the message
1919 * @param message the actual message
1920 * @param atsi performance data for the connection
1921 * @return #GNUNET_OK to keep the connection open,
1922 * #GNUNET_SYSERR to close it (signal serious error)
1925 handle_service_request_multipart (void *cls,
1926 struct GNUNET_MESH_Tunnel * tunnel,
1928 const struct GNUNET_MessageHeader * message)
1930 struct ServiceSession * session;
1931 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1932 uint32_t used_elements;
1933 uint32_t contained_elements=0;
1934 uint32_t msg_length;
1935 unsigned char * current;
1939 // are we in the correct state?
1940 session = (struct ServiceSession *) * tunnel_ctx;
1941 if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
1944 // shorter than minimum?
1945 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1948 used_elements = session->used;
1949 contained_elements = ntohl (msg->multipart_element_count);
1950 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1951 + contained_elements * PAILLIER_ELEMENT_LENGTH;
1953 if (( ntohs (msg->header.size) != msg_length)
1954 || (used_elements < contained_elements + session->transferred)) {
1957 current = (unsigned char *) &msg[1];
1958 if (contained_elements != 0) {
1959 // Convert each vector element to MPI_value
1960 for (i = session->transferred; i < session->transferred+contained_elements; i++) {
1962 if (0 != (rc = gcry_mpi_scan (&session->a[i],
1964 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1965 PAILLIER_ELEMENT_LENGTH,
1967 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1971 session->transferred+=contained_elements;
1973 if (session->transferred == used_elements) {
1974 // single part finished
1975 session->state = SERVICE_REQUEST_RECEIVED;
1976 if (session->response) {
1977 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1978 if (GNUNET_OK != compute_service_response (session, session->response)) {
1979 //something went wrong, remove it again...
1984 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1987 // multipart message
1993 // and notify our client-session that we could not complete the session
1994 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1995 if (session->response)
1996 // we just found the responder session in this queue
1997 session->response->client_notification_task =
1998 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2000 free_session_variables (session);
2001 GNUNET_free (session);
2002 return GNUNET_SYSERR;
2006 * Handle a request from another service to calculate a scalarproduct with us.
2008 * @param cls closure (set from #GNUNET_MESH_connect)
2009 * @param tunnel connection to the other end
2010 * @param tunnel_ctx place to store local state associated with the tunnel
2011 * @param sender who sent the message
2012 * @param message the actual message
2013 * @param atsi performance data for the connection
2014 * @return #GNUNET_OK to keep the connection open,
2015 * #GNUNET_SYSERR to close it (signal serious error)
2018 handle_service_request (void *cls,
2019 struct GNUNET_MESH_Tunnel * tunnel,
2021 const struct GNUNET_MessageHeader * message)
2023 struct ServiceSession * session;
2024 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2025 uint32_t mask_length;
2027 uint32_t used_elements;
2028 uint32_t contained_elements = 0;
2029 uint32_t element_count;
2030 uint32_t msg_length;
2031 unsigned char * current;
2034 enum SessionState needed_state;
2036 session = (struct ServiceSession *) * tunnel_ctx;
2037 if (WAITING_FOR_SERVICE_REQUEST != session->state) {
2040 // Check if message was sent by me, which would be bad!
2041 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2042 GNUNET_free (session);
2044 return GNUNET_SYSERR;
2046 // shorter than expected?
2047 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2048 GNUNET_free (session);
2049 GNUNET_break_op (0);
2050 return GNUNET_SYSERR;
2052 mask_length = ntohl (msg->mask_length);
2053 pk_length = ntohl (msg->pk_length);
2054 used_elements = ntohl (msg->total_element_count);
2055 contained_elements = ntohl (msg->contained_element_count);
2056 element_count = ntohl (msg->element_count);
2057 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2058 +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2060 //sanity check: is the message as long as the message_count fields suggests?
2061 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2062 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2064 GNUNET_free (session);
2065 GNUNET_break_op (0);
2066 return GNUNET_SYSERR;
2068 if (find_matching_session (from_service_tail,
2073 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2074 GNUNET_free (session);
2075 return GNUNET_SYSERR;
2078 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2079 session->total = element_count;
2080 session->used = used_elements;
2081 session->transferred = contained_elements;
2082 session->tunnel = tunnel;
2085 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2086 current = (unsigned char *) &msg[1];
2087 //preserve the mask, we will need that later on
2088 session->mask = GNUNET_malloc (mask_length);
2089 memcpy (session->mask, current, mask_length);
2091 current += mask_length;
2093 //convert the publickey to sexp
2094 if (0 != (rc = gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))) {
2095 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_sexp_new", rc);
2096 GNUNET_free (session->mask);
2097 GNUNET_free (session);
2098 return GNUNET_SYSERR;
2100 current += pk_length;
2101 //check if service queue contains a matching request
2102 needed_state = CLIENT_RESPONSE_RECEIVED;
2103 session->response = find_matching_session (from_client_tail,
2106 &needed_state, NULL);
2108 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2109 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2110 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2111 if (contained_elements != 0) {
2112 // Convert each vector element to MPI_value
2113 for (i = 0; i < contained_elements; i++) {
2115 if (0 != (rc = gcry_mpi_scan (&session->a[i],
2117 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2118 PAILLIER_ELEMENT_LENGTH,
2120 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2124 if (contained_elements == used_elements) {
2125 // single part finished
2126 session->state = SERVICE_REQUEST_RECEIVED;
2127 if (session->response) {
2128 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2129 if (GNUNET_OK != compute_service_response (session, session->response)) {
2130 //something went wrong, remove it again...
2135 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2138 // multipart message
2143 GNUNET_break_op (0);
2144 if ((NULL != session->next) || (NULL != session->prev) || (from_service_head == session))
2145 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2146 // and notify our client-session that we could not complete the session
2147 if (session->response)
2148 // we just found the responder session in this queue
2149 session->response->client_notification_task =
2150 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2152 free_session_variables (session);
2153 return GNUNET_SYSERR;
2157 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2159 * @param cls closure (set from #GNUNET_MESH_connect)
2160 * @param tunnel connection to the other end
2161 * @param tunnel_ctx place to store local state associated with the tunnel
2162 * @param sender who sent the message
2163 * @param message the actual message
2164 * @param atsi performance data for the connection
2165 * @return #GNUNET_OK to keep the connection open,
2166 * #GNUNET_SYSERR to close it (signal serious error)
2169 handle_service_response_multipart (void *cls,
2170 struct GNUNET_MESH_Tunnel * tunnel,
2172 const struct GNUNET_MessageHeader * message)
2174 struct ServiceSession * session;
2175 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2176 unsigned char * current;
2179 uint32_t contained=0;
2183 GNUNET_assert (NULL != message);
2184 // are we in the correct state?
2185 session = (struct ServiceSession *) * tunnel_ctx;
2186 if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2189 // shorter than minimum?
2190 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2193 contained = ntohl (msg->multipart_element_count);
2194 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2195 + 2 * contained * PAILLIER_ELEMENT_LENGTH;
2196 //sanity check: is the message as long as the message_count fields suggests?
2197 if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2200 current = (unsigned char *) &msg[1];
2201 // Convert each k[][perm] to its MPI_value
2202 for (i = 0; i < contained; i++) {
2203 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2204 PAILLIER_ELEMENT_LENGTH, &read))) {
2205 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2208 current += PAILLIER_ELEMENT_LENGTH;
2209 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2210 PAILLIER_ELEMENT_LENGTH, &read))) {
2211 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2214 current += PAILLIER_ELEMENT_LENGTH;
2216 session->transferred += contained;
2217 if (session->transferred != session->used)
2219 session->state = SERVICE_RESPONSE_RECEIVED;
2220 session->product = compute_scalar_product (session);
2221 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2224 GNUNET_break_op (0);
2225 free_session_variables (session);
2226 session->state = FINALIZED;
2227 session->tunnel = NULL;
2228 // send message with product to client
2229 if (ALICE == session->role)
2230 session->client_notification_task =
2231 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2233 // the tunnel has done its job, terminate our connection and the tunnel
2234 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2235 // just close the connection, as recommended by Christian
2236 return GNUNET_SYSERR;
2240 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2242 * @param cls closure (set from #GNUNET_MESH_connect)
2243 * @param tunnel connection to the other end
2244 * @param tunnel_ctx place to store local state associated with the tunnel
2245 * @param sender who sent the message
2246 * @param message the actual message
2247 * @param atsi performance data for the connection
2248 * @return #GNUNET_OK to keep the connection open,
2249 * #GNUNET_SYSERR to close it (we are done)
2252 handle_service_response (void *cls,
2253 struct GNUNET_MESH_Tunnel * tunnel,
2255 const struct GNUNET_MessageHeader * message)
2257 struct ServiceSession * session;
2258 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2259 unsigned char * current;
2262 uint32_t contained=0;
2266 GNUNET_assert (NULL != message);
2267 session = (struct ServiceSession *) * tunnel_ctx;
2268 // are we in the correct state?
2269 if (session->state != WAITING_FOR_SERVICE_REQUEST) {
2272 //we need at least a full message without elements attached
2273 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) + 2 * PAILLIER_ELEMENT_LENGTH > ntohs (msg->header.size)) {
2276 contained = ntohl (msg->contained_element_count);
2277 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2278 + 2 * contained * PAILLIER_ELEMENT_LENGTH
2279 + 2 * PAILLIER_ELEMENT_LENGTH;
2280 //sanity check: is the message as long as the message_count fields suggests?
2281 if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2284 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2285 session->transferred = contained;
2287 current = (unsigned char *) &msg[1];
2288 if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2289 PAILLIER_ELEMENT_LENGTH, &read))) {
2290 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2293 current += PAILLIER_ELEMENT_LENGTH;
2295 if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2296 PAILLIER_ELEMENT_LENGTH, &read))) {
2297 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2300 current += PAILLIER_ELEMENT_LENGTH;
2301 session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2302 session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2303 // Convert each k[][perm] to its MPI_value
2304 for (i = 0; i < contained; i++) {
2305 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2306 PAILLIER_ELEMENT_LENGTH, &read))) {
2307 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2310 current += PAILLIER_ELEMENT_LENGTH;
2311 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2312 PAILLIER_ELEMENT_LENGTH, &read))) {
2313 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2316 current += PAILLIER_ELEMENT_LENGTH;
2318 if (session->transferred != session->used)
2319 return GNUNET_OK; //wait for the other multipart chunks
2321 session->state = SERVICE_RESPONSE_RECEIVED;
2322 session->product = compute_scalar_product (session);
2323 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2326 GNUNET_break_op (0);
2327 free_session_variables (session);
2328 session->state = FINALIZED;
2329 session->tunnel = NULL;
2330 // send message with product to client
2331 if (ALICE == session->role)
2332 session->client_notification_task =
2333 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2335 // the tunnel has done its job, terminate our connection and the tunnel
2336 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2337 // just close the connection, as recommended by Christian
2338 return GNUNET_SYSERR;
2342 * Task run during shutdown.
2348 shutdown_task (void *cls,
2349 const struct GNUNET_SCHEDULER_TaskContext *tc)
2351 struct ServiceSession * session;
2352 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2354 do_shutdown = GNUNET_YES;
2356 // terminate all owned open tunnels.
2357 for (session = from_client_head; NULL != session; session = session->next) {
2358 if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2359 GNUNET_MESH_tunnel_destroy (session->tunnel);
2360 session->tunnel = NULL;
2362 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2363 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2364 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2366 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2367 GNUNET_SCHEDULER_cancel (session->service_request_task);
2368 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2370 if (NULL != session->client) {
2371 GNUNET_SERVER_client_disconnect (session->client);
2372 session->client = NULL;
2375 for (session = from_service_head; NULL != session; session = session->next)
2376 if (NULL != session->tunnel) {
2377 GNUNET_MESH_tunnel_destroy (session->tunnel);
2378 session->tunnel = NULL;
2382 GNUNET_MESH_disconnect (my_mesh);
2388 * Initialization of the program and message handlers
2390 * @param cls closure
2391 * @param server the initialized server
2392 * @param c configuration to use
2396 struct GNUNET_SERVER_Handle *server,
2397 const struct GNUNET_CONFIGURATION_Handle *c)
2399 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2400 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2401 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2404 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2405 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2406 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2407 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2408 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2411 static const uint32_t ports[] = {
2412 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2415 //generate private/public key set
2416 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2418 // register server callbacks and disconnect handler
2419 GNUNET_SERVER_add_handlers (server, server_handlers);
2420 GNUNET_SERVER_disconnect_notify (server,
2421 &handle_client_disconnect,
2423 GNUNET_break (GNUNET_OK ==
2424 GNUNET_CRYPTO_get_peer_identity (c,
2426 my_mesh = GNUNET_MESH_connect (c, NULL,
2427 &tunnel_incoming_handler,
2428 &tunnel_destruction_handler,
2429 mesh_handlers, ports);
2431 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2432 GNUNET_SCHEDULER_shutdown ();
2435 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2436 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2442 * The main function for the scalarproduct service.
2444 * @param argc number of arguments from the command line
2445 * @param argv command line arguments
2446 * @return 0 ok, 1 on error
2449 main (int argc, char *const *argv)
2451 return (GNUNET_OK ==
2452 GNUNET_SERVICE_run (argc, argv,
2454 GNUNET_SERVICE_OPTION_NONE,
2455 &run, NULL)) ? 0 : 1;
2458 /* end of gnunet-service-ext.c */