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 (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_non_null (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_non_null(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_non_null(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);
727 GNUNET_free (session);
729 ///////////////////////////////////////////////////////////////////////////////
730 // Event and Message Handlers
731 ///////////////////////////////////////////////////////////////////////////////
734 * A client disconnected.
736 * Remove the associated session(s), release datastructures
737 * and cancel pending outgoing transmissions to the client.
738 * if the session has not yet completed, we also cancel Alice's request to Bob.
740 * @param cls closure, NULL
741 * @param client identification of the client
744 handle_client_disconnect (void *cls,
745 struct GNUNET_SERVER_Client *client)
747 struct ServiceSession *session;
751 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755 _ ("Client (%p) disconnected from us.\n"), client);
756 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
758 if (!(session->role == BOB && session->state == FINALIZED)) {
759 //we MUST terminate any client message underway
760 if (session->service_transmit_handle && session->tunnel)
761 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
762 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
763 GNUNET_MESH_tunnel_destroy (session->tunnel);
765 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
766 GNUNET_SCHEDULER_cancel (session->client_notification_task);
767 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
769 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
770 GNUNET_SCHEDULER_cancel (session->service_request_task);
771 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
773 if (NULL != session->client_transmit_handle) {
774 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
775 session->client_transmit_handle = NULL;
777 free_session (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 (session);
1499 //we need at least a peer and one message id to compare
1500 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1501 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1502 _ ("Too short message received from client!\n"));
1503 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1507 msg_type = ntohs (msg->header.type);
1508 element_count = ntohl (msg->element_count);
1509 mask_length = ntohl (msg->mask_length);
1511 //sanity check: is the message as long as the message_count fields suggests?
1512 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1513 || (0 == element_count)) {
1514 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1515 _ ("Invalid message received from client, session information incorrect!\n"));
1516 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1520 // do we have a duplicate session here already?
1521 if (NULL != find_matching_session (from_client_tail,
1525 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1526 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1527 GNUNET_h2s (&msg->key));
1528 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1532 session = GNUNET_new (struct ServiceSession);
1533 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1534 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1535 session->client = client;
1536 session->total = element_count;
1537 session->mask_length = mask_length;
1538 // get our transaction key
1539 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1540 //allocate memory for vector and encrypted vector
1541 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1542 vector = (int32_t *) & msg[1];
1544 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1547 GNUNET_h2s (&session->key));
1549 session->role = ALICE;
1551 session->mask = GNUNET_malloc (mask_length);
1552 memcpy (session->mask, &vector[element_count], mask_length);
1554 // copy over the elements
1556 for (i = 0; i < element_count; i++) {
1557 session->vector[i] = ntohl (vector[i]);
1558 if (session->vector[i] == 0)
1559 session->mask[i / 8] &= ~(1 << (i % 8));
1560 if (session->mask[i / 8] & (1 << (i % 8)))
1564 if (0 == session->used) {
1565 GNUNET_break_op (0);
1566 GNUNET_free (session->vector);
1567 GNUNET_free (session);
1568 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1571 //session with ourself makes no sense!
1572 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1574 GNUNET_free (session->vector);
1575 GNUNET_free (session);
1576 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1580 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1581 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1582 _ ("Creating new tunnel to for session with key %s.\n"),
1583 GNUNET_h2s (&session->key));
1584 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1586 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1589 //prepare_service_request, tunnel_peer_disconnect_handler,
1590 if (!session->tunnel) {
1592 GNUNET_free (session->vector);
1593 GNUNET_free (session);
1594 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1597 GNUNET_SERVER_client_set_user_context (client, session);
1598 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1600 session->state = CLIENT_REQUEST_RECEIVED;
1601 session->service_request_task =
1602 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1607 struct ServiceSession * requesting_session;
1608 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1610 session->role = BOB;
1611 session->mask = NULL;
1612 // copy over the elements
1613 session->used = element_count;
1614 for (i = 0; i < element_count; i++)
1615 session->vector[i] = ntohl (vector[i]);
1616 session->state = CLIENT_RESPONSE_RECEIVED;
1618 GNUNET_SERVER_client_set_user_context (client, session);
1619 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1621 //check if service queue contains a matching request
1622 requesting_session = find_matching_session (from_service_tail,
1625 &needed_state, NULL);
1626 if (NULL != requesting_session) {
1627 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));
1628 if (GNUNET_OK != compute_service_response (requesting_session, session))
1629 session->client_notification_task =
1630 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1635 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));
1636 // no matching session exists yet, store the response
1637 // for later processing by handle_service_request()
1640 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1644 * Function called for inbound tunnels.
1646 * @param cls closure
1647 * @param tunnel new handle to the tunnel
1648 * @param initiator peer that started the tunnel
1649 * @param atsi performance information for the tunnel
1650 * @return initial tunnel context for the tunnel
1651 * (can be NULL -- that's not an error)
1654 tunnel_incoming_handler (void *cls,
1655 struct GNUNET_MESH_Tunnel *tunnel,
1656 const struct GNUNET_PeerIdentity *initiator,
1659 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1661 c->peer = *initiator;
1664 c->state = WAITING_FOR_SERVICE_REQUEST;
1669 * Function called whenever a tunnel is destroyed. Should clean up
1670 * any associated state.
1672 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1674 * @param cls closure (set from GNUNET_MESH_connect)
1675 * @param tunnel connection to the other end (henceforth invalid)
1676 * @param tunnel_ctx place where local state associated
1677 * with the tunnel is stored
1680 tunnel_destruction_handler (void *cls,
1681 const struct GNUNET_MESH_Tunnel *tunnel,
1684 struct ServiceSession * session = tunnel_ctx;
1685 struct ServiceSession * client_session;
1686 struct ServiceSession * curr;
1688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1690 GNUNET_h2s (&session->key),
1691 GNUNET_i2s (&session->peer));
1692 if (ALICE == session->role) {
1693 // as we have only one peer connected in each session, just remove the session
1695 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1696 session->tunnel = NULL;
1697 // if this happened before we received the answer, we must terminate the session
1698 session->client_notification_task =
1699 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1703 else { //(BOB == session->role) service session
1704 // remove the session, unless it has already been dequeued, but somehow still active
1705 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1706 // scenario: disconnect before alice can send her message to bob.
1707 for (curr = from_service_head; NULL != curr; curr = curr->next)
1708 if (curr == session) {
1709 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1712 // there is a client waiting for this service session, terminate it, too!
1713 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1714 client_session = find_matching_session (from_client_tail,
1718 free_session (session);
1720 // the client has to check if it was waiting for a result
1721 // or if it was a responder, no point in adding more statefulness
1722 if (client_session && (!do_shutdown)) {
1723 client_session->state = FINALIZED;
1724 client_session->client_notification_task =
1725 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1732 * Compute our scalar product, done by Alice
1734 * @param session - the session associated with this computation
1735 * @param kp - (1) from the protocol definition:
1736 * $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)})$
1737 * @param kq - (2) from the protocol definition:
1738 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1739 * @param s - S from the protocol definition:
1740 * $S := E_A(\sum (r_i + b_i)^2)$
1741 * @param stick - S' from the protocol definition:
1742 * $S' := E_A(\sum r_i^2)$
1743 * @return product as MPI, never NULL
1746 compute_scalar_product (struct ServiceSession * session)
1757 count = session->used;
1758 tmp = gcry_mpi_new (KEYBITS);
1759 // due to the introduced static offset S, we now also have to remove this
1760 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1761 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1762 for (i = 0; i < count; i++) {
1763 decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1764 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1765 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1766 decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1767 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1768 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1771 // calculate t = sum(ai)
1772 t = compute_square_sum (session->a, count);
1775 u = gcry_mpi_new (0);
1776 tmp = compute_square_sum (session->r, count);
1777 gcry_mpi_sub (u, u, tmp);
1778 gcry_mpi_release (tmp);
1781 utick = gcry_mpi_new (0);
1782 tmp = compute_square_sum (session->r_prime, count);
1783 gcry_mpi_sub (utick, utick, tmp);
1785 GNUNET_assert (p = gcry_mpi_new (0));
1786 GNUNET_assert (ptick = gcry_mpi_new (0));
1789 decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1790 decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1793 gcry_mpi_add (p, session->s, t);
1794 gcry_mpi_add (p, p, u);
1797 gcry_mpi_add (ptick, session->s_prime, t);
1798 gcry_mpi_add (ptick, ptick, utick);
1800 gcry_mpi_release (t);
1801 gcry_mpi_release (u);
1802 gcry_mpi_release (utick);
1805 gcry_mpi_sub (p, p, ptick);
1806 gcry_mpi_release (ptick);
1807 tmp = gcry_mpi_set_ui (tmp, 2);
1808 gcry_mpi_div (p, NULL, p, tmp, 0);
1810 gcry_mpi_release (tmp);
1811 for (i = 0; i < count; i++)
1812 gcry_mpi_release (session->a[i]);
1813 GNUNET_free (session->a);
1820 * prepare the response we will send to alice or bobs' clients.
1821 * in Bobs case the product will be NULL.
1823 * @param session the session associated with our client.
1826 prepare_client_response (void *cls,
1827 const struct GNUNET_SCHEDULER_TaskContext *tc)
1829 struct ServiceSession * session = cls;
1830 struct GNUNET_SCALARPRODUCT_client_response * msg;
1831 unsigned char * product_exported = NULL;
1832 size_t product_length = 0;
1833 uint32_t msg_length = 0;
1838 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1840 if (session->product) {
1841 gcry_mpi_t value = gcry_mpi_new (0);
1843 sign = gcry_mpi_cmp_ui (session->product, 0);
1844 // libgcrypt can not handle a print of a negative number
1845 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1847 gcry_mpi_sub (value, value, session->product);
1849 else if (0 < sign) {
1851 gcry_mpi_add (value, value, session->product);
1856 gcry_mpi_release (session->product);
1857 session->product = NULL;
1859 // get representation as string
1861 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1865 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1867 range = -1; // signal error with product-length = 0 and range = -1
1869 gcry_mpi_release (value);
1872 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1873 msg = GNUNET_malloc (msg_length);
1874 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1875 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1876 if (product_exported != NULL) {
1877 memcpy (&msg[1], product_exported, product_length);
1878 GNUNET_free (product_exported);
1880 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1881 msg->header.size = htons (msg_length);
1883 msg->product_length = htonl (product_length);
1885 session->msg = (struct GNUNET_MessageHeader *) msg;
1886 //transmit this message to our client
1887 session->client_transmit_handle =
1888 GNUNET_SERVER_notify_transmit_ready (session->client,
1890 GNUNET_TIME_UNIT_FOREVER_REL,
1893 if (NULL == session->client_transmit_handle) {
1894 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1895 _ ("Could not send message to client (%p)!\n"),
1897 session->client = NULL;
1898 // callback was not called!
1900 session->msg = NULL;
1903 // gracefully sent message, just terminate session structure
1904 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1905 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1907 GNUNET_h2s (&session->key));
1911 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1913 * @param cls closure (set from #GNUNET_MESH_connect)
1914 * @param tunnel connection to the other end
1915 * @param tunnel_ctx place to store local state associated with the tunnel
1916 * @param sender who sent the message
1917 * @param message the actual message
1918 * @param atsi performance data for the connection
1919 * @return #GNUNET_OK to keep the connection open,
1920 * #GNUNET_SYSERR to close it (signal serious error)
1923 handle_service_request_multipart (void *cls,
1924 struct GNUNET_MESH_Tunnel * tunnel,
1926 const struct GNUNET_MessageHeader * message)
1928 struct ServiceSession * session;
1929 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1930 uint32_t used_elements;
1931 uint32_t contained_elements=0;
1932 uint32_t msg_length;
1933 unsigned char * current;
1936 // are we in the correct state?
1937 session = (struct ServiceSession *) * tunnel_ctx;
1938 if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
1941 // shorter than minimum?
1942 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1945 used_elements = session->used;
1946 contained_elements = ntohl (msg->multipart_element_count);
1947 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1948 + contained_elements * PAILLIER_ELEMENT_LENGTH;
1950 if (( ntohs (msg->header.size) != msg_length)
1951 || (used_elements < contained_elements + session->transferred)) {
1954 current = (unsigned char *) &msg[1];
1955 if (contained_elements != 0) {
1956 gcry_error_t ret = 0;
1957 // Convert each vector element to MPI_value
1958 for (i = session->transferred; i < session->transferred+contained_elements; i++) {
1961 ret = gcry_mpi_scan (&session->a[i],
1963 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1964 PAILLIER_ELEMENT_LENGTH,
1967 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1968 i, gcry_strsource (ret), gcry_strerror (ret));
1972 session->transferred+=contained_elements;
1974 if (session->transferred == used_elements) {
1975 // single part finished
1976 session->state = SERVICE_REQUEST_RECEIVED;
1977 if (session->response) {
1978 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1979 if (GNUNET_OK != compute_service_response (session, session->response)) {
1980 //something went wrong, remove it again...
1981 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1986 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1989 // multipart message
1995 // and notify our client-session that we could not complete the session
1996 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1997 if (session->response)
1998 // we just found the responder session in this queue
1999 session->response->client_notification_task =
2000 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2002 free_session (session);
2003 return GNUNET_SYSERR;
2007 * Handle a request from another service to calculate a scalarproduct with us.
2009 * @param cls closure (set from #GNUNET_MESH_connect)
2010 * @param tunnel connection to the other end
2011 * @param tunnel_ctx place to store local state associated with the tunnel
2012 * @param sender who sent the message
2013 * @param message the actual message
2014 * @param atsi performance data for the connection
2015 * @return #GNUNET_OK to keep the connection open,
2016 * #GNUNET_SYSERR to close it (signal serious error)
2019 handle_service_request (void *cls,
2020 struct GNUNET_MESH_Tunnel * tunnel,
2022 const struct GNUNET_MessageHeader * message)
2024 struct ServiceSession * session;
2025 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2026 uint32_t mask_length;
2028 uint32_t used_elements;
2029 uint32_t contained_elements = 0;
2030 uint32_t element_count;
2031 uint32_t msg_length;
2032 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 (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1)) {
2095 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
2096 GNUNET_free (session->mask);
2097 GNUNET_free (session);
2098 return GNUNET_SYSERR;
2101 current += pk_length;
2103 //check if service queue contains a matching request
2104 needed_state = CLIENT_RESPONSE_RECEIVED;
2105 session->response = find_matching_session (from_client_tail,
2108 &needed_state, NULL);
2110 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2111 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2112 if (contained_elements != 0) {
2113 gcry_error_t ret = 0;
2114 // Convert each vector element to MPI_value
2115 for (i = 0; i < contained_elements; i++) {
2118 ret = gcry_mpi_scan (&session->a[i],
2120 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2121 PAILLIER_ELEMENT_LENGTH,
2124 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
2125 i, gcry_strsource (ret), gcry_strerror (ret));
2129 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2131 if (contained_elements == used_elements) {
2132 // single part finished
2133 session->state = SERVICE_REQUEST_RECEIVED;
2134 if (session->response) {
2135 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2136 if (GNUNET_OK != compute_service_response (session, session->response)) {
2137 //something went wrong, remove it again...
2138 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2143 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2146 // multipart message
2151 GNUNET_break_op (0);
2152 // and notify our client-session that we could not complete the session
2153 if (session->response)
2154 // we just found the responder session in this queue
2155 session->response->client_notification_task =
2156 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2158 free_session (session);
2159 return GNUNET_SYSERR;
2163 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2165 * @param cls closure (set from #GNUNET_MESH_connect)
2166 * @param tunnel connection to the other end
2167 * @param tunnel_ctx place to store local state associated with the tunnel
2168 * @param sender who sent the message
2169 * @param message the actual message
2170 * @param atsi performance data for the connection
2171 * @return #GNUNET_OK to keep the connection open,
2172 * #GNUNET_SYSERR to close it (signal serious error)
2175 handle_service_response_multipart (void *cls,
2176 struct GNUNET_MESH_Tunnel * tunnel,
2178 const struct GNUNET_MessageHeader * message)
2180 struct ServiceSession * session;
2181 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2182 unsigned char * current;
2185 uint32_t contained=0;
2189 GNUNET_assert (NULL != message);
2190 // are we in the correct state?
2191 session = (struct ServiceSession *) * tunnel_ctx;
2192 if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2193 GNUNET_break_op (0);
2196 // shorter than minimum?
2197 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2200 contained = ntohl (msg->multipart_element_count);
2201 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2202 + 2 * contained * PAILLIER_ELEMENT_LENGTH;
2203 //sanity check: is the message as long as the message_count fields suggests?
2204 if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2207 current = (unsigned char *) &msg[1];
2208 // Convert each k[][perm] to its MPI_value
2209 for (i = 0; i < contained; i++) {
2210 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2211 PAILLIER_ELEMENT_LENGTH, &read))) {
2212 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2213 GNUNET_break_op (0);
2216 current += PAILLIER_ELEMENT_LENGTH;
2217 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2218 PAILLIER_ELEMENT_LENGTH, &read))) {
2219 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2220 GNUNET_break_op (0);
2223 current += PAILLIER_ELEMENT_LENGTH;
2225 session->transferred += contained;
2226 if (session->transferred != session->used)
2228 session->state = SERVICE_RESPONSE_RECEIVED;
2229 session->product = compute_scalar_product (session);
2230 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2233 GNUNET_break_op (0);
2235 gcry_mpi_release (session->s);
2236 if (session->s_prime)
2237 gcry_mpi_release (session->s_prime);
2239 for (i = 0; session->r && i < session->used; i++)
2240 if (session->r[i]) gcry_mpi_release (session->r[i]);
2241 if (session->r_prime)
2242 for (i = 0; session->r_prime && i < session->used; i++)
2243 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2245 for (i = 0; session->a && i < session->used; i++)
2246 if (session->a[i]) gcry_mpi_release (session->a[i]);
2247 GNUNET_free_non_null (session->r);
2248 GNUNET_free_non_null (session->r_prime);
2249 GNUNET_free_non_null (session->a);
2252 session->s_prime = NULL;
2254 session->r_prime = NULL;
2255 session->tunnel = NULL;
2256 // send message with product to client
2257 session->client_notification_task =
2258 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2260 // the tunnel has done its job, terminate our connection and the tunnel
2261 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2262 // just close the connection, as recommended by Christian
2263 return GNUNET_SYSERR;
2267 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2269 * @param cls closure (set from #GNUNET_MESH_connect)
2270 * @param tunnel connection to the other end
2271 * @param tunnel_ctx place to store local state associated with the tunnel
2272 * @param sender who sent the message
2273 * @param message the actual message
2274 * @param atsi performance data for the connection
2275 * @return #GNUNET_OK to keep the connection open,
2276 * #GNUNET_SYSERR to close it (we are done)
2279 handle_service_response (void *cls,
2280 struct GNUNET_MESH_Tunnel * tunnel,
2282 const struct GNUNET_MessageHeader * message)
2284 struct ServiceSession * session;
2285 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2286 unsigned char * current;
2289 uint32_t contained=0;
2293 GNUNET_assert (NULL != message);
2294 session = (struct ServiceSession *) * tunnel_ctx;
2295 // are we in the correct state?
2296 if (session->state != WAITING_FOR_SERVICE_REQUEST) {
2299 //we need at least a full message without elements attached
2300 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) + 2 * PAILLIER_ELEMENT_LENGTH > ntohs (msg->header.size)) {
2303 contained = ntohl (msg->contained_element_count);
2304 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2305 + 2 * contained * PAILLIER_ELEMENT_LENGTH
2306 + 2 * PAILLIER_ELEMENT_LENGTH;
2307 //sanity check: is the message as long as the message_count fields suggests?
2308 if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2311 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2312 session->transferred = contained;
2314 current = (unsigned char *) &msg[1];
2315 if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2316 PAILLIER_ELEMENT_LENGTH, &read))) {
2317 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2320 current += PAILLIER_ELEMENT_LENGTH;
2322 if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2323 PAILLIER_ELEMENT_LENGTH, &read))) {
2324 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2327 current += PAILLIER_ELEMENT_LENGTH;
2328 session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2329 session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2330 // Convert each k[][perm] to its MPI_value
2331 for (i = 0; i < contained; i++) {
2332 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2333 PAILLIER_ELEMENT_LENGTH, &read))) {
2334 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2337 current += PAILLIER_ELEMENT_LENGTH;
2338 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2339 PAILLIER_ELEMENT_LENGTH, &read))) {
2340 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2343 current += PAILLIER_ELEMENT_LENGTH;
2345 if (session->transferred != session->used)
2346 return GNUNET_OK; //wait for the other multipart chunks
2348 session->state = SERVICE_RESPONSE_RECEIVED;
2349 session->product = compute_scalar_product (session);
2350 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2353 GNUNET_break_op (0);
2355 gcry_mpi_release (session->s);
2356 if (session->s_prime)
2357 gcry_mpi_release (session->s_prime);
2359 for (i = 0; session->r && i < session->used; i++)
2360 if (session->r[i]) gcry_mpi_release (session->r[i]);
2361 if (session->r_prime)
2362 for (i = 0; session->r_prime && i < session->used; i++)
2363 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2365 for (i = 0; session->a && i < session->used; i++)
2366 if (session->a[i]) gcry_mpi_release (session->a[i]);
2367 GNUNET_free_non_null (session->r);
2368 GNUNET_free_non_null (session->r_prime);
2369 GNUNET_free_non_null (session->a);
2372 session->s_prime = NULL;
2374 session->r_prime = NULL;
2375 session->tunnel = NULL;
2376 // send message with product to client
2377 session->client_notification_task =
2378 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2380 // the tunnel has done its job, terminate our connection and the tunnel
2381 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2382 // just close the connection, as recommended by Christian
2383 return GNUNET_SYSERR;
2387 * Task run during shutdown.
2393 shutdown_task (void *cls,
2394 const struct GNUNET_SCHEDULER_TaskContext *tc)
2396 struct ServiceSession * session;
2397 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2399 do_shutdown = GNUNET_YES;
2401 // terminate all owned open tunnels.
2402 for (session = from_client_head; NULL != session; session = session->next) {
2403 if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2404 GNUNET_MESH_tunnel_destroy (session->tunnel);
2405 session->tunnel = NULL;
2407 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2408 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2409 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2411 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2412 GNUNET_SCHEDULER_cancel (session->service_request_task);
2413 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2415 if (NULL != session->client) {
2416 GNUNET_SERVER_client_disconnect (session->client);
2417 session->client = NULL;
2420 for (session = from_service_head; NULL != session; session = session->next)
2421 if (NULL != session->tunnel) {
2422 GNUNET_MESH_tunnel_destroy (session->tunnel);
2423 session->tunnel = NULL;
2427 GNUNET_MESH_disconnect (my_mesh);
2433 * Initialization of the program and message handlers
2435 * @param cls closure
2436 * @param server the initialized server
2437 * @param c configuration to use
2441 struct GNUNET_SERVER_Handle *server,
2442 const struct GNUNET_CONFIGURATION_Handle *c)
2444 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2445 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2446 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2449 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2450 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2451 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2452 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2453 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2456 static const uint32_t ports[] = {
2457 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2460 //generate private/public key set
2461 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2463 // register server callbacks and disconnect handler
2464 GNUNET_SERVER_add_handlers (server, server_handlers);
2465 GNUNET_SERVER_disconnect_notify (server,
2466 &handle_client_disconnect,
2468 GNUNET_break (GNUNET_OK ==
2469 GNUNET_CRYPTO_get_peer_identity (c,
2471 my_mesh = GNUNET_MESH_connect (c, NULL,
2472 &tunnel_incoming_handler,
2473 &tunnel_destruction_handler,
2474 mesh_handlers, ports);
2476 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2477 GNUNET_SCHEDULER_shutdown ();
2480 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2481 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2487 * The main function for the scalarproduct service.
2489 * @param argc number of arguments from the command line
2490 * @param argv command line arguments
2491 * @return 0 ok, 1 on error
2494 main (int argc, char *const *argv)
2496 return (GNUNET_OK ==
2497 GNUNET_SERVICE_run (argc, argv,
2499 GNUNET_SERVICE_OPTION_NONE,
2500 &run, NULL)) ? 0 : 1;
2503 /* end of gnunet-service-ext.c */