2 This file is part of GNUnet.
3 (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file scalarproduct/gnunet-service-scalarproduct.c
23 * @brief scalarproduct service implementation
24 * @author Christian M. Fuchs
28 #include "gnunet_util_lib.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_mesh_service.h"
31 #include "gnunet_applications.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_scalarproduct_service.h"
34 #include "scalarproduct.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
38 ///////////////////////////////////////////////////////////////////////////////
39 // Service Structure Definitions
40 ///////////////////////////////////////////////////////////////////////////////
43 * state a session can be in
47 CLIENT_REQUEST_RECEIVED,
48 WAITING_FOR_BOBS_CONNECT,
49 CLIENT_RESPONSE_RECEIVED,
50 WAITING_FOR_SERVICE_REQUEST,
51 WAITING_FOR_MULTIPART_TRANSMISSION,
52 WAITING_FOR_SERVICE_RESPONSE,
53 SERVICE_REQUEST_RECEIVED,
54 SERVICE_RESPONSE_RECEIVED,
59 * role a peer in a session can assume
68 * A scalarproduct session which tracks:
70 * a request form the client to our final response.
72 * a request from a service to us(service).
77 * the role this peer has
82 * session information is kept in a DLL
84 struct ServiceSession *next;
87 * session information is kept in a DLL
89 struct ServiceSession *prev;
92 * (hopefully) unique transaction ID
94 struct GNUNET_HashCode key;
97 * state of the session
99 enum SessionState state;
102 * Alice or Bob's peerID
104 struct GNUNET_PeerIdentity peer;
107 * the client this request is related to
109 struct GNUNET_SERVER_Client * client;
112 * The message to send
114 struct GNUNET_MessageHeader * msg;
117 * how many elements we were supplied with from the client
119 uint32_t element_count;
122 * how many elements actually are used after applying the mask
124 uint32_t used_element_count;
127 * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
129 uint32_t transferred_element_count;
132 * index of the last transferred element for multipart messages
134 uint32_t last_processed_element;
137 * how many bytes the mask is long.
138 * just for convenience so we don't have to re-re-re calculate it each time
140 uint32_t mask_length;
143 * all the vector elements we received
148 * mask of which elements to check
150 unsigned char * mask;
153 * Public key of the remote service, only used by bob
155 gcry_sexp_t remote_pubkey;
158 * E(ai)(Bob) or ai(Alice) after applying the mask
163 * Bob's permutation p of R
168 * Bob's permutation q of R
170 gcry_mpi_t * r_prime;
173 * Bobs matching response session from the client
175 struct ServiceSession * response;
178 * The computed scalar
183 * My transmit handle for the current message to a alice/bob
185 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
188 * My transmit handle for the current message to the client
190 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
193 * tunnel-handle associated with our mesh handle
195 struct GNUNET_MESH_Tunnel * tunnel;
197 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
199 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
202 ///////////////////////////////////////////////////////////////////////////////
204 ///////////////////////////////////////////////////////////////////////////////
208 * Handle to the core service (NULL until we've connected to it).
210 static struct GNUNET_MESH_Handle *my_mesh;
213 * The identity of this host.
215 static struct GNUNET_PeerIdentity me;
218 * Service's own public key represented as string
220 static unsigned char * my_pubkey_external;
223 * Service's own public key represented as string
225 static uint32_t my_pubkey_external_length = 0;
230 static gcry_mpi_t my_n;
233 * Service's own n^2 (kept for performance)
235 static gcry_mpi_t my_nsquare;
238 * Service's own public exponent
240 static gcry_mpi_t my_g;
243 * Service's own private multiplier
245 static gcry_mpi_t my_mu;
248 * Service's own private exponent
250 static gcry_mpi_t my_lambda;
253 * Service's offset for values that could possibly be negative but are plaintext for encryption.
255 static gcry_mpi_t my_offset;
258 * Head of our double linked list for client-requests sent to us.
259 * for all of these elements we calculate a scalar product with a remote peer
260 * split between service->service and client->service for simplicity
262 static struct ServiceSession * from_client_head;
264 * Tail of our double linked list for client-requests sent to us.
265 * for all of these elements we calculate a scalar product with a remote peer
266 * split between service->service and client->service for simplicity
268 static struct ServiceSession * from_client_tail;
271 * Head of our double linked list for service-requests sent to us.
272 * for all of these elements we help the requesting service in calculating a scalar product
273 * split between service->service and client->service for simplicity
275 static struct ServiceSession * from_service_head;
278 * Tail of our double linked list for service-requests sent to us.
279 * for all of these elements we help the requesting service in calculating a scalar product
280 * split between service->service and client->service for simplicity
282 static struct ServiceSession * from_service_tail;
285 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
287 static int do_shutdown;
289 ///////////////////////////////////////////////////////////////////////////////
291 ///////////////////////////////////////////////////////////////////////////////
295 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
300 gcry_sexp_t gen_params;
302 gcry_sexp_t tmp_sexp;
311 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
312 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
313 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
316 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
317 gcry_sexp_release (gen_params);
319 // get n and d of our publickey as MPI
320 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
321 GNUNET_assert (tmp_sexp);
322 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
323 gcry_sexp_release (tmp_sexp);
324 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
325 GNUNET_assert (tmp_sexp);
326 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
327 gcry_sexp_release (tmp_sexp);
328 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
329 GNUNET_assert (tmp_sexp);
330 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
331 gcry_sexp_release (key);
333 tmp1 = gcry_mpi_new (0);
334 tmp2 = gcry_mpi_new (0);
335 gcd = gcry_mpi_new (0);
336 my_g = gcry_mpi_new (0);
337 my_mu = gcry_mpi_new (0);
338 my_nsquare = gcry_mpi_new (0);
339 my_lambda = gcry_mpi_new (0);
342 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
343 gcry_mpi_sub_ui (tmp1, p, 1);
344 gcry_mpi_sub_ui (tmp2, q, 1);
345 gcry_mpi_gcd (gcd, tmp1, tmp2);
346 gcry_mpi_set (my_lambda, tmp1);
347 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
348 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
351 gcry_mpi_mul (my_nsquare, my_n, my_n);
357 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
358 // g must be smaller than n^2
359 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
362 // g must have gcd == 1 with n^2
363 gcry_mpi_gcd (gcd, my_g, my_nsquare);
365 while (gcry_mpi_cmp_ui (gcd, 1));
367 // is this a valid g?
368 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
369 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
370 gcry_mpi_sub_ui (tmp1, tmp1, 1);
371 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
372 gcry_mpi_gcd (gcd, tmp1, my_n);
374 while (gcry_mpi_cmp_ui (gcd, 1));
376 // calculate our mu based on g and n.
377 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
378 gcry_mpi_invm (my_mu, tmp1, my_n);
380 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
381 "(public-key (paillier (n %M)(g %M)))",
384 // get the length of this sexpression
385 my_pubkey_external_length = gcry_sexp_sprint (key,
390 GNUNET_assert (my_pubkey_external_length > 0);
391 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
393 // convert the sexpression to canonical format
394 gcry_sexp_sprint (key,
397 my_pubkey_external_length);
399 gcry_sexp_release (key);
401 // offset has to be sufficiently small to allow computation of:
402 // m1+m2 mod n == (S + a) + (S + b) mod n,
403 // if we have more complex operations, this factor needs to be lowered
404 my_offset = gcry_mpi_new (KEYBITS / 3);
405 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
412 * If target != size, move target bytes to the
413 * end of the size-sized buffer and zero out the
414 * first target-size bytes.
416 * @param buf original buffer
417 * @param size number of bytes in the buffer
418 * @param target target size of the buffer
421 adjust (unsigned char *buf, size_t size, size_t target)
425 memmove (&buf[target - size], buf, size);
426 memset (buf, 0, target - size);
432 * encrypts an element using the paillier crypto system
434 * @param c ciphertext (output)
436 * @param g the public base
437 * @param n the module from which which r is chosen (Z*_n)
438 * @param n_square the module for encryption, for performance reasons.
441 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
445 GNUNET_assert (tmp = gcry_mpi_new (0));
447 while (0 >= gcry_mpi_cmp_ui (tmp, 1))
449 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
450 // r must be 1 < r < n
453 gcry_mpi_powm (c, g, m, n_square);
454 gcry_mpi_powm (tmp, tmp, n, n_square);
455 gcry_mpi_mulm (c, tmp, c, n_square);
457 gcry_mpi_release (tmp);
462 * decrypts an element using the paillier crypto system
464 * @param m plaintext (output)
465 * @param c the ciphertext
466 * @param mu the modifier to correct encryption
467 * @param lambda the private exponent
468 * @param n the outer module for decryption
469 * @param n_square the inner module for decryption
472 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)
474 gcry_mpi_powm (m, c, lambda, n_square);
475 gcry_mpi_sub_ui (m, m, 1);
476 gcry_mpi_div (m, NULL, m, n, 0);
477 gcry_mpi_mulm (m, m, mu, n);
482 * computes the square sum over a vector of a given length.
484 * @param vector the vector to encrypt
485 * @param length the length of the vector
486 * @return an MPI value containing the calculated sum, never NULL
489 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
495 GNUNET_assert (sum = gcry_mpi_new (0));
496 GNUNET_assert (elem = gcry_mpi_new (0));
498 // calculare E(sum (ai ^ 2), publickey)
499 for (i = 0; i < length; i++)
501 gcry_mpi_mul (elem, vector[i], vector[i]);
502 gcry_mpi_add (sum, sum, elem);
504 gcry_mpi_release (elem);
511 prepare_service_request_multipart (void *cls,
512 const struct GNUNET_SCHEDULER_TaskContext *tc);
514 prepare_service_response_multipart (void *cls,
515 const struct GNUNET_SCHEDULER_TaskContext *tc);
518 * Primitive callback for copying over a message, as they
519 * usually are too complex to be handled in the callback itself.
520 * clears a session-callback, if a session was handed over and the transmit handle was stored
522 * @param cls the message object
523 * @param size the size of the buffer we got
524 * @param buf the buffer to copy the message to
525 * @return 0 if we couldn't copy, else the size copied over
528 do_send_message (void *cls, size_t size, void *buf)
530 struct ServiceSession * session = cls;
535 if (ntohs (session->msg->size) == size)
537 memcpy (buf, session->msg, size);
541 switch (ntohs (session->msg->type))
543 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
544 session->state = FINALIZED;
545 session->client_transmit_handle = NULL;
547 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
548 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
550 session->service_transmit_handle = NULL;
551 // reset flags for sending
552 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
553 prepare_service_request_multipart(session, NULL);
554 //TODO we have sent a message and now need to trigger trigger the next multipart message sending
556 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
557 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
559 session->service_transmit_handle = NULL;
560 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
561 prepare_service_response_multipart(session, NULL);
564 session->service_transmit_handle = NULL;
567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
568 "Sent a message of type %hu.\n",
569 ntohs (session->msg->type));
570 GNUNET_free (session->msg);
578 * initializes a new vector with fresh MPI values (=0) of a given length
580 * @param length of the vector to create
581 * @return the initialized vector, never NULL
584 initialize_mpi_vector (uint32_t length)
587 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
589 for (i = 0; i < length; i++)
590 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
596 * permutes an MPI vector according to the given permutation vector
598 * @param vector the vector to permuted
599 * @param perm the permutation to use
600 * @param length the length of the vectors
601 * @return the permuted vector (same as input), never NULL
604 permute_vector (gcry_mpi_t * vector,
608 gcry_mpi_t tmp[length];
611 GNUNET_assert (length > 0);
614 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
616 // permute vector according to given
617 for (i = 0; i < length; i++)
618 vector[i] = tmp[perm[i]];
625 * Populate a vector with random integer values and convert them to
627 * @param length the length of the vector we must generate
628 * @return an array of MPI values with random values
631 generate_random_vector (uint32_t length)
633 gcry_mpi_t * random_vector;
637 random_vector = initialize_mpi_vector (length);
638 for (i = 0; i < length; i++)
640 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
642 // long to gcry_mpi_t
644 gcry_mpi_sub_ui (random_vector[i],
648 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
651 return random_vector;
656 * Finds a not terminated client/service session in the
657 * given DLL based on session key, element count and state.
659 * @param tail - the tail of the DLL
660 * @param my - the session to compare it to
661 * @return a pointer to a matching session,
664 static struct ServiceSession *
665 find_matching_session (struct ServiceSession * tail,
666 const struct GNUNET_HashCode * key,
667 uint32_t element_count,
668 enum SessionState * state,
669 const struct GNUNET_PeerIdentity * peerid)
671 struct ServiceSession * curr;
673 for (curr = tail; NULL != curr; curr = curr->prev)
675 // if the key matches, and the element_count is same
676 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
677 && (curr->element_count == element_count))
679 // if incoming state is NULL OR is same as state of the queued request
680 if ((NULL == state) || (curr->state == *state))
682 // if peerid is NULL OR same as the peer Id in the queued request
684 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
685 // matches and is not an already terminated session
696 free_session (struct ServiceSession * session)
702 for (i = 0; i < session->used_element_count; i++)
703 gcry_mpi_release (session->a[i]);
705 GNUNET_free (session->a);
707 if (session->product)
708 gcry_mpi_release (session->product);
710 if (session->remote_pubkey)
711 gcry_sexp_release (session->remote_pubkey);
713 GNUNET_free_non_null (session->vector);
714 GNUNET_free (session);
716 ///////////////////////////////////////////////////////////////////////////////
717 // Event and Message Handlers
718 ///////////////////////////////////////////////////////////////////////////////
722 * A client disconnected.
724 * Remove the associated session(s), release datastructures
725 * and cancel pending outgoing transmissions to the client.
726 * if the session has not yet completed, we also cancel Alice's request to Bob.
728 * @param cls closure, NULL
729 * @param client identification of the client
732 handle_client_disconnect (void *cls,
733 struct GNUNET_SERVER_Client *client)
735 struct ServiceSession *session;
739 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
743 _ ("Client (%p) disconnected from us.\n"), client);
744 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
746 if (!(session->role == BOB && session->state == FINALIZED))
748 //we MUST terminate any client message underway
749 if (session->service_transmit_handle && session->tunnel)
750 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
751 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
752 GNUNET_MESH_tunnel_destroy (session->tunnel);
754 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task)
756 GNUNET_SCHEDULER_cancel (session->client_notification_task);
757 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
759 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task)
761 GNUNET_SCHEDULER_cancel (session->service_request_task);
762 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
764 if (NULL != session->client_transmit_handle)
766 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
767 session->client_transmit_handle = NULL;
769 free_session (session);
774 * Notify the client that the session has succeeded or failed completely.
775 * This message gets sent to
776 * * alice's client if bob disconnected or to
777 * * bob's client if the operation completed or alice disconnected
779 * @param client_session the associated client session
780 * @return GNUNET_NO, if we could not notify the client
781 * GNUNET_YES if we notified it.
784 prepare_client_end_notification (void * cls,
785 const struct GNUNET_SCHEDULER_TaskContext * tc)
787 struct ServiceSession * session = cls;
788 struct GNUNET_SCALARPRODUCT_client_response * msg;
790 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
792 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
793 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
794 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
795 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
796 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
797 // signal error if not signalized, positive result-range field but zero length.
798 msg->product_length = htonl (0);
799 msg->range = (session->state == FINALIZED) ? 0 : -1;
801 session->msg = &msg->header;
803 //transmit this message to our client
804 session->client_transmit_handle =
805 GNUNET_SERVER_notify_transmit_ready (session->client,
806 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
807 GNUNET_TIME_UNIT_FOREVER_REL,
811 // if we could not even queue our request, something is wrong
812 if (NULL == session->client_transmit_handle)
814 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
815 // usually gets freed by do_send_message
820 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
825 prepare_service_response_multipart (void *cls,
826 const struct GNUNET_SCHEDULER_TaskContext *tc)
828 struct ServiceSession * session = cls;
829 unsigned char * current;
830 unsigned char * element_exported;
831 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
835 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
837 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
838 todo_count = session->used_element_count - session->transferred_element_count;
840 if (todo_count > MULTIPART_ELEMENT_CAPACITY/2)
841 // send the currently possible maximum chunk, we always transfer both permutations
842 todo_count = MULTIPART_ELEMENT_CAPACITY/2;
844 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
845 msg = GNUNET_malloc (msg_length);
846 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
847 msg->header.size = htons (msg_length);
848 msg->multipart_element_count = htonl (todo_count);
850 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
851 current = (unsigned char *) &msg[1];
853 for (i = session->transferred_element_count; i < session->transferred_element_count + todo_count; i++)
856 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
857 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
858 element_exported, PAILLIER_ELEMENT_LENGTH,
861 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
862 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
863 current += PAILLIER_ELEMENT_LENGTH;
865 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
866 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
867 element_exported, PAILLIER_ELEMENT_LENGTH,
869 session->r_prime[i]));
870 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
871 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
872 current += PAILLIER_ELEMENT_LENGTH;
874 GNUNET_free (element_exported);
875 for (i = session->transferred_element_count; i < session->transferred_element_count; i++)
877 gcry_mpi_release (session->r_prime[i]);
878 gcry_mpi_release (session->r[i]);
880 session->transferred_element_count+=todo_count;
881 session->msg = (struct GNUNET_MessageHeader *) msg;
882 session->service_transmit_handle =
883 GNUNET_MESH_notify_transmit_ready (session->tunnel,
885 GNUNET_TIME_UNIT_FOREVER_REL,
889 //disconnect our client
890 if (NULL == session->service_transmit_handle)
892 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
893 session->state = FINALIZED;
895 session->response->client_notification_task =
896 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
900 if (session->transferred_element_count != session->used_element_count)
902 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
905 session->state = FINALIZED;
910 * generates the response message to be sent to alice after computing
911 * the values (1), (2), S and S'
912 * (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)})$
913 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
914 * S: $S := E_A(sum (r_i + b_i)^2)$
915 * S': $S' := E_A(sum r_i^2)$
917 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
918 * @param s_prime S': $S' := E_A(sum r_i^2)$
919 * @param session the associated requesting session with alice
920 * @return GNUNET_NO if we could not send our message
921 * GNUNET_OK if the operation succeeded
924 prepare_service_response (gcry_mpi_t s,
926 struct ServiceSession * session)
928 struct GNUNET_SCALARPRODUCT_service_response * msg;
929 uint32_t msg_length = 0;
930 unsigned char * current = NULL;
931 unsigned char * element_exported = NULL;
932 size_t element_length = 0;
935 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
936 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
938 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH){ //kp, kq
939 msg_length += + 2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH;
940 session->transferred_element_count = session->used_element_count;
943 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
946 msg = GNUNET_malloc (msg_length);
948 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
949 msg->header.size = htons (msg_length);
950 msg->total_element_count = htonl (session->element_count);
951 msg->contained_element_count = htonl (session->used_element_count);
952 msg->contained_element_count = htonl (session->transferred_element_count);
953 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
954 current = (unsigned char *) &msg[1];
956 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
957 // 4 times the same logics with slight variations.
958 // doesn't really justify having 2 functions for that
959 // so i put it into blocks to enhance readability
961 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
962 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
963 element_exported, PAILLIER_ELEMENT_LENGTH,
966 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
967 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
968 current += PAILLIER_ELEMENT_LENGTH;
971 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
972 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
973 element_exported, PAILLIER_ELEMENT_LENGTH,
976 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
977 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
978 current += PAILLIER_ELEMENT_LENGTH;
981 for (i = 0; i < session->transferred_element_count; i++)
984 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
985 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
986 element_exported, PAILLIER_ELEMENT_LENGTH,
989 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
990 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
991 current += PAILLIER_ELEMENT_LENGTH;
993 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
994 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
995 element_exported, PAILLIER_ELEMENT_LENGTH,
997 session->r_prime[i]));
998 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
999 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1000 current += PAILLIER_ELEMENT_LENGTH;
1003 GNUNET_free (element_exported);
1004 for (i = 0; i < session->transferred_element_count; i++)
1006 gcry_mpi_release (session->r_prime[i]);
1007 gcry_mpi_release (session->r[i]);
1009 gcry_mpi_release (s);
1010 gcry_mpi_release (s_prime);
1012 session->msg = (struct GNUNET_MessageHeader *) msg;
1013 session->service_transmit_handle =
1014 GNUNET_MESH_notify_transmit_ready (session->tunnel,
1016 GNUNET_TIME_UNIT_FOREVER_REL,
1020 //disconnect our client
1021 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_element_count != session->used_element_count)
1033 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1036 session->state = FINALIZED;
1044 * compute the values
1045 * (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)})$
1046 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1047 * S: $S := E_A(\sum (r_i + b_i)^2)$
1048 * S': $S' := E_A(\sum r_i^2)$
1050 * @param request the requesting session + bob's requesting peer
1051 * @param response the responding session + bob's client handle
1052 * @return GNUNET_SYSERR if the computation failed
1053 * GNUNET_OK if everything went well.
1056 compute_service_response (struct ServiceSession * request,
1057 struct ServiceSession * response)
1061 int ret = GNUNET_SYSERR;
1065 gcry_mpi_t * rand = NULL;
1066 gcry_mpi_t * r = NULL;
1067 gcry_mpi_t * r_prime = NULL;
1070 gcry_mpi_t * a_pi_prime;
1072 gcry_mpi_t * rand_pi;
1073 gcry_mpi_t * rand_pi_prime;
1074 gcry_mpi_t s = NULL;
1075 gcry_mpi_t s_prime = NULL;
1076 gcry_mpi_t remote_n = NULL;
1077 gcry_mpi_t remote_nsquare;
1078 gcry_mpi_t remote_g = NULL;
1079 gcry_sexp_t tmp_exp;
1082 count = request->used_element_count;
1084 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1085 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1086 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1087 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1088 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1089 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1091 // convert responder session to from long to mpi
1092 for (i = 0, j = 0; i < response->element_count && j < count; i++)
1094 if (request->mask[i / 8] & (1 << (i % 8)))
1096 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1097 // long to gcry_mpi_t
1098 if (0 > response->vector[i])
1100 b[j] = gcry_mpi_new (0);
1101 gcry_mpi_sub_ui (b[j], b[j], value);
1105 b[j] = gcry_mpi_set_ui (NULL, value);
1110 GNUNET_free (response->vector);
1111 response->vector = NULL;
1113 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1116 GNUNET_break_op (0);
1117 gcry_sexp_release (request->remote_pubkey);
1118 request->remote_pubkey = NULL;
1121 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1125 gcry_sexp_release (tmp_exp);
1128 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1129 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1130 gcry_sexp_release (tmp_exp);
1131 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1132 gcry_sexp_release (request->remote_pubkey);
1133 request->remote_pubkey = NULL;
1136 GNUNET_break_op (0);
1137 gcry_mpi_release (remote_n);
1140 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1144 gcry_mpi_release (remote_n);
1145 gcry_sexp_release (tmp_exp);
1148 gcry_sexp_release (tmp_exp);
1150 // generate r, p and q
1151 rand = generate_random_vector (count);
1152 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1153 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1154 //initialize the result vectors
1155 r = initialize_mpi_vector (count);
1156 r_prime = initialize_mpi_vector (count);
1158 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1159 // those values, thus we can work with the references
1160 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1161 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1162 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1163 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1164 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1166 // generate p and q permutations for a, b and r
1167 GNUNET_assert (permute_vector (a_pi, p, count));
1168 GNUNET_assert (permute_vector (b_pi, p, count));
1169 GNUNET_assert (permute_vector (rand_pi, p, count));
1170 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1171 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1173 // encrypt the element
1174 // for the sake of readability I decided to have dedicated permutation
1175 // vectors, which get rid of all the lookups in p/q.
1176 // however, ap/aq are not absolutely necessary but are just abstraction
1177 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1178 for (i = 0; i < count; i++)
1180 // E(S - r_pi - b_pi)
1181 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1182 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1183 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1185 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1186 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1190 GNUNET_free (rand_pi);
1192 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1193 for (i = 0; i < count; i++)
1196 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1197 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1199 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1200 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1202 GNUNET_free (a_pi_prime);
1203 GNUNET_free (rand_pi_prime);
1206 request->r_prime = r_prime;
1207 request->response = response;
1209 // Calculate S' = E(SUM( r_i^2 ))
1210 s_prime = compute_square_sum (rand, count);
1211 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1213 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1214 for (i = 0; i < count; i++)
1216 gcry_mpi_add (rand[i], rand[i], b[i]);
1218 s = compute_square_sum (rand, count);
1219 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1220 gcry_mpi_release (remote_n);
1221 gcry_mpi_release (remote_g);
1222 gcry_mpi_release (remote_nsquare);
1224 // release r and tmp
1225 for (i = 0; i < count; i++)
1226 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1227 gcry_mpi_release (rand[i]);
1229 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1230 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1231 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1232 GNUNET_i2s (&request->peer));
1237 for (i = 0; i < count; i++)
1239 gcry_mpi_release (b[i]);
1240 gcry_mpi_release (request->a[i]);
1244 GNUNET_free (request->a);
1251 prepare_service_request_multipart (void *cls,
1252 const struct GNUNET_SCHEDULER_TaskContext *tc)
1254 struct ServiceSession * session = cls;
1255 unsigned char * current;
1256 unsigned char * element_exported;
1257 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1260 uint32_t msg_length;
1261 uint32_t todo_count;
1262 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1266 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1267 todo_count = session->used_element_count - session->transferred_element_count;
1269 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1270 // send the currently possible maximum chunk
1271 todo_count = MULTIPART_ELEMENT_CAPACITY;
1273 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1274 msg = GNUNET_malloc (msg_length);
1275 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1276 msg->header.size = htons (msg_length);
1277 msg->multipart_element_count = htonl (todo_count);
1279 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1280 a = gcry_mpi_new (KEYBITS * 2);
1281 current = (unsigned char *) &msg[1];
1282 // encrypt our vector and generate string representations
1283 for (i = session->last_processed_element, j = 0; i < session->element_count; i++)
1285 // is this a used element?
1286 if (session->mask[i / 8] & 1 << (i % 8))
1288 if (todo_count <= j)
1289 break; //reached end of this message, can't include more
1291 memset(element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1292 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1294 a = gcry_mpi_set_ui (a, 0);
1295 // long to gcry_mpi_t
1296 if (session->vector[i] < 0)
1297 gcry_mpi_sub_ui (a, a, value);
1299 gcry_mpi_add_ui (a, a, value);
1301 session->a[session->transferred_element_count + j++] = gcry_mpi_set (NULL, a);
1302 gcry_mpi_add (a, a, my_offset);
1303 encrypt_element (a, a, my_g, my_n, my_nsquare);
1305 // get representation as string
1306 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1307 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1308 element_exported, PAILLIER_ELEMENT_LENGTH,
1312 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1313 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1315 // copy over to the message
1316 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1317 current += PAILLIER_ELEMENT_LENGTH;
1320 gcry_mpi_release (a);
1321 GNUNET_free(element_exported);
1322 session->transferred_element_count+=todo_count;
1324 session->msg = (struct GNUNET_MessageHeader *) msg;
1325 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1327 //transmit via mesh messaging
1328 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1329 GNUNET_TIME_UNIT_FOREVER_REL,
1333 if (!session->service_transmit_handle)
1335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1337 session->msg = NULL;
1338 session->client_notification_task =
1339 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1343 if (session->transferred_element_count != session->used_element_count){
1344 session->last_processed_element = i;
1348 session->state = WAITING_FOR_SERVICE_RESPONSE;
1352 * Executed by Alice, fills in a service-request message and sends it to the given peer
1354 * @param session the session associated with this request, then also holds the CORE-handle
1355 * @return #GNUNET_SYSERR if we could not send the message
1356 * #GNUNET_NO if the message was too large
1357 * #GNUNET_OK if we sent it
1360 prepare_service_request (void *cls,
1361 const struct GNUNET_SCHEDULER_TaskContext *tc)
1363 struct ServiceSession * session = cls;
1364 unsigned char * current;
1365 unsigned char * element_exported;
1366 struct GNUNET_SCALARPRODUCT_service_request * msg;
1369 uint32_t msg_length;
1370 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1374 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1378 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1379 + session->mask_length
1380 + my_pubkey_external_length;
1382 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used_element_count * PAILLIER_ELEMENT_LENGTH){
1383 msg_length += session->used_element_count * PAILLIER_ELEMENT_LENGTH;
1384 session->transferred_element_count = session->used_element_count;
1387 //create a multipart msg, first we calculate a new msg size for the head msg
1388 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1391 msg = GNUNET_malloc (msg_length);
1392 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1393 msg->total_element_count = htonl(session->used_element_count);
1394 msg->contained_element_count = htonl (session->transferred_element_count);
1395 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1396 msg->mask_length = htonl (session->mask_length);
1397 msg->pk_length = htonl (my_pubkey_external_length);
1398 msg->element_count = htonl (session->element_count);
1399 msg->header.size = htons (msg_length);
1401 // fill in the payload
1402 current = (unsigned char *) &msg[1];
1403 // copy over the mask
1404 memcpy (current, session->mask, session->mask_length);
1405 // copy over our public key
1406 current += session->mask_length;
1407 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1408 current += my_pubkey_external_length;
1410 // now copy over the element vector
1411 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1412 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1413 a = gcry_mpi_new (KEYBITS * 2);
1414 // encrypt our vector and generate string representations
1415 for (i = 0, j = 0; i < session->element_count; i++)
1417 // if this is a used element...
1418 if (session->mask[i / 8] & 1 << (i % 8))
1420 if (session->transferred_element_count <= j)
1421 break; //reached end of this message, can't include more
1423 memset(element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1424 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1426 a = gcry_mpi_set_ui (a, 0);
1427 // long to gcry_mpi_t
1428 if (session->vector[i] < 0)
1429 gcry_mpi_sub_ui (a, a, value);
1431 gcry_mpi_add_ui (a, a, value);
1433 session->a[j++] = gcry_mpi_set (NULL, a);
1434 gcry_mpi_add (a, a, my_offset);
1435 encrypt_element (a, a, my_g, my_n, my_nsquare);
1437 // get representation as string
1438 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1439 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1440 element_exported, PAILLIER_ELEMENT_LENGTH,
1444 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1445 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1447 // copy over to the message
1448 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1449 current += PAILLIER_ELEMENT_LENGTH;
1452 gcry_mpi_release (a);
1453 GNUNET_free(element_exported);
1455 session->msg = (struct GNUNET_MessageHeader *) msg;
1456 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1458 //transmit via mesh messaging
1459 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1460 GNUNET_TIME_UNIT_FOREVER_REL,
1464 if (!session->service_transmit_handle)
1466 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1468 session->msg = NULL;
1469 session->client_notification_task =
1470 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1474 if (session->transferred_element_count != session->used_element_count){
1475 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1476 session->last_processed_element = i;
1479 //singlepart message
1480 session->state = WAITING_FOR_SERVICE_RESPONSE;
1485 * Handler for a client request message.
1486 * Can either be type A or B
1487 * A: request-initiation to compute a scalar product with a peer
1488 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1490 * @param cls closure
1491 * @param client identification of the client
1492 * @param message the actual message
1495 handle_client_request (void *cls,
1496 struct GNUNET_SERVER_Client *client,
1497 const struct GNUNET_MessageHeader *message)
1499 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1500 struct ServiceSession * session;
1501 uint32_t element_count;
1502 uint32_t mask_length;
1507 // only one concurrent session per client connection allowed, simplifies logics a lot...
1508 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1509 if ((NULL != session) && (session->state != FINALIZED))
1511 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1514 else if (NULL != session)
1516 // old session is already completed, clean it up
1517 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1518 free_session (session);
1521 //we need at least a peer and one message id to compare
1522 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size))
1524 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1525 _ ("Too short message received from client!\n"));
1526 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1530 msg_type = ntohs (msg->header.type);
1531 element_count = ntohl (msg->element_count);
1532 mask_length = ntohl (msg->mask_length);
1534 //sanity check: is the message as long as the message_count fields suggests?
1535 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1536 || (0 == element_count))
1538 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1539 _ ("Invalid message received from client, session information incorrect!\n"));
1540 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1544 // do we have a duplicate session here already?
1545 if (NULL != find_matching_session (from_client_tail,
1550 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1551 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1552 GNUNET_h2s (&msg->key));
1553 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1557 session = GNUNET_new (struct ServiceSession);
1558 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1559 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1560 session->client = client;
1561 session->element_count = element_count;
1562 session->mask_length = mask_length;
1563 // get our transaction key
1564 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1565 //allocate memory for vector and encrypted vector
1566 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1567 vector = (int32_t *) & msg[1];
1569 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type)
1571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1573 GNUNET_h2s (&session->key));
1575 session->role = ALICE;
1577 session->mask = GNUNET_malloc (mask_length);
1578 memcpy (session->mask, &vector[element_count], mask_length);
1580 // copy over the elements
1581 session->used_element_count = 0;
1582 for (i = 0; i < element_count; i++)
1584 session->vector[i] = ntohl (vector[i]);
1585 if (session->vector[i] == 0)
1586 session->mask[i / 8] &= ~(1 << (i % 8));
1587 if (session->mask[i / 8] & (1 << (i % 8)))
1588 session->used_element_count++;
1591 if (0 == session->used_element_count)
1593 GNUNET_break_op (0);
1594 GNUNET_free (session->vector);
1595 GNUNET_free (session);
1596 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1599 //session with ourself makes no sense!
1600 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1603 GNUNET_free (session->vector);
1604 GNUNET_free (session);
1605 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1609 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1610 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1611 _ ("Creating new tunnel to for session with key %s.\n"),
1612 GNUNET_h2s (&session->key));
1613 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1615 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1618 //prepare_service_request, tunnel_peer_disconnect_handler,
1619 if (!session->tunnel)
1622 GNUNET_free (session->vector);
1623 GNUNET_free (session);
1624 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1627 GNUNET_SERVER_client_set_user_context (client, session);
1628 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1630 session->state = CLIENT_REQUEST_RECEIVED;
1631 session->service_request_task =
1632 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1638 struct ServiceSession * requesting_session;
1639 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1641 session->role = BOB;
1642 session->mask = NULL;
1643 // copy over the elements
1644 session->used_element_count = element_count;
1645 for (i = 0; i < element_count; i++)
1646 session->vector[i] = ntohl (vector[i]);
1647 session->state = CLIENT_RESPONSE_RECEIVED;
1649 GNUNET_SERVER_client_set_user_context (client, session);
1650 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1652 //check if service queue contains a matching request
1653 requesting_session = find_matching_session (from_service_tail,
1655 session->element_count,
1656 &needed_state, NULL);
1657 if (NULL != requesting_session)
1659 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));
1660 if (GNUNET_OK != compute_service_response (requesting_session, session))
1661 session->client_notification_task =
1662 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1668 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));
1669 // no matching session exists yet, store the response
1670 // for later processing by handle_service_request()
1673 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1678 * Function called for inbound tunnels.
1680 * @param cls closure
1681 * @param tunnel new handle to the tunnel
1682 * @param initiator peer that started the tunnel
1683 * @param atsi performance information for the tunnel
1684 * @return initial tunnel context for the tunnel
1685 * (can be NULL -- that's not an error)
1688 tunnel_incoming_handler (void *cls,
1689 struct GNUNET_MESH_Tunnel *tunnel,
1690 const struct GNUNET_PeerIdentity *initiator,
1693 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1695 c->peer = *initiator;
1698 c->state = WAITING_FOR_SERVICE_REQUEST;
1704 * Function called whenever a tunnel is destroyed. Should clean up
1705 * any associated state.
1707 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1709 * @param cls closure (set from GNUNET_MESH_connect)
1710 * @param tunnel connection to the other end (henceforth invalid)
1711 * @param tunnel_ctx place where local state associated
1712 * with the tunnel is stored
1715 tunnel_destruction_handler (void *cls,
1716 const struct GNUNET_MESH_Tunnel *tunnel,
1719 struct ServiceSession * session = tunnel_ctx;
1720 struct ServiceSession * client_session;
1721 struct ServiceSession * curr;
1723 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1724 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1725 GNUNET_h2s (&session->key),
1726 GNUNET_i2s (&session->peer));
1727 if (ALICE == session->role)
1729 // as we have only one peer connected in each session, just remove the session
1731 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown))
1733 session->tunnel = NULL;
1734 // if this happened before we received the answer, we must terminate the session
1735 session->client_notification_task =
1736 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1741 { //(BOB == session->role) service session
1742 // remove the session, unless it has already been dequeued, but somehow still active
1743 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1744 // scenario: disconnect before alice can send her message to bob.
1745 for (curr = from_service_head; NULL != curr; curr = curr->next)
1746 if (curr == session)
1748 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1751 // there is a client waiting for this service session, terminate it, too!
1752 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1753 client_session = find_matching_session (from_client_tail,
1755 session->element_count,
1757 free_session (session);
1759 // the client has to check if it was waiting for a result
1760 // or if it was a responder, no point in adding more statefulness
1761 if (client_session && (!do_shutdown))
1763 client_session->state = FINALIZED;
1764 client_session->client_notification_task =
1765 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1773 * Compute our scalar product, done by Alice
1775 * @param session - the session associated with this computation
1776 * @param kp - (1) from the protocol definition:
1777 * $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)})$
1778 * @param kq - (2) from the protocol definition:
1779 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1780 * @param s - S from the protocol definition:
1781 * $S := E_A(\sum (r_i + b_i)^2)$
1782 * @param stick - S' from the protocol definition:
1783 * $S' := E_A(\sum r_i^2)$
1784 * @return product as MPI, never NULL
1787 compute_scalar_product (struct ServiceSession * session,
1788 gcry_mpi_t * r, gcry_mpi_t * r_prime, gcry_mpi_t s, gcry_mpi_t s_prime)
1799 count = session->used_element_count;
1800 tmp = gcry_mpi_new (KEYBITS);
1801 // due to the introduced static offset S, we now also have to remove this
1802 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1803 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1804 for (i = 0; i < count; i++)
1806 decrypt_element (r[i], r[i], my_mu, my_lambda, my_n, my_nsquare);
1807 gcry_mpi_sub (r[i], r[i], my_offset);
1808 gcry_mpi_sub (r[i], r[i], my_offset);
1809 decrypt_element (r_prime[i], r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1810 gcry_mpi_sub (r_prime[i], r_prime[i], my_offset);
1811 gcry_mpi_sub (r_prime[i], r_prime[i], my_offset);
1814 // calculate t = sum(ai)
1815 t = compute_square_sum (session->a, count);
1818 u = gcry_mpi_new (0);
1819 tmp = compute_square_sum (r, count);
1820 gcry_mpi_sub (u, u, tmp);
1821 gcry_mpi_release (tmp);
1824 utick = gcry_mpi_new (0);
1825 tmp = compute_square_sum (r_prime, count);
1826 gcry_mpi_sub (utick, utick, tmp);
1828 GNUNET_assert (p = gcry_mpi_new (0));
1829 GNUNET_assert (ptick = gcry_mpi_new (0));
1832 decrypt_element (s, s, my_mu, my_lambda, my_n, my_nsquare);
1833 decrypt_element (s_prime, s_prime, my_mu, my_lambda, my_n, my_nsquare);
1836 gcry_mpi_add (p, s, t);
1837 gcry_mpi_add (p, p, u);
1840 gcry_mpi_add (ptick, s_prime, t);
1841 gcry_mpi_add (ptick, ptick, utick);
1843 gcry_mpi_release (t);
1844 gcry_mpi_release (u);
1845 gcry_mpi_release (utick);
1848 gcry_mpi_sub (p, p, ptick);
1849 gcry_mpi_release (ptick);
1850 tmp = gcry_mpi_set_ui (tmp, 2);
1851 gcry_mpi_div (p, NULL, p, tmp, 0);
1853 gcry_mpi_release (tmp);
1854 for (i = 0; i < count; i++)
1855 gcry_mpi_release (session->a[i]);
1856 GNUNET_free (session->a);
1864 * prepare the response we will send to alice or bobs' clients.
1865 * in Bobs case the product will be NULL.
1867 * @param session the session associated with our client.
1870 prepare_client_response (void *cls,
1871 const struct GNUNET_SCHEDULER_TaskContext *tc)
1873 struct ServiceSession * session = cls;
1874 struct GNUNET_SCALARPRODUCT_client_response * msg;
1875 unsigned char * product_exported = NULL;
1876 size_t product_length = 0;
1877 uint32_t msg_length = 0;
1882 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1884 if (session->product)
1886 gcry_mpi_t value = gcry_mpi_new (0);
1888 sign = gcry_mpi_cmp_ui (session->product, 0);
1889 // libgcrypt can not handle a print of a negative number
1890 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1893 gcry_mpi_sub (value, value, session->product);
1898 gcry_mpi_add (value, value, session->product);
1903 gcry_mpi_release (session->product);
1904 session->product = NULL;
1906 // get representation as string
1908 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1913 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1915 range = -1; // signal error with product-length = 0 and range = -1
1917 gcry_mpi_release (value);
1920 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1921 msg = GNUNET_malloc (msg_length);
1922 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1923 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1924 if (product_exported != NULL)
1926 memcpy (&msg[1], product_exported, product_length);
1927 GNUNET_free (product_exported);
1929 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1930 msg->header.size = htons (msg_length);
1932 msg->product_length = htonl (product_length);
1934 session->msg = (struct GNUNET_MessageHeader *) msg;
1935 //transmit this message to our client
1936 session->client_transmit_handle =
1937 GNUNET_SERVER_notify_transmit_ready (session->client,
1939 GNUNET_TIME_UNIT_FOREVER_REL,
1942 if (NULL == session->client_transmit_handle)
1944 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1945 _ ("Could not send message to client (%p)!\n"),
1947 session->client = NULL;
1948 // callback was not called!
1950 session->msg = NULL;
1953 // gracefully sent message, just terminate session structure
1954 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1955 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1957 GNUNET_h2s (&session->key));
1961 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1963 * @param cls closure (set from #GNUNET_MESH_connect)
1964 * @param tunnel connection to the other end
1965 * @param tunnel_ctx place to store local state associated with the tunnel
1966 * @param sender who sent the message
1967 * @param message the actual message
1968 * @param atsi performance data for the connection
1969 * @return #GNUNET_OK to keep the connection open,
1970 * #GNUNET_SYSERR to close it (signal serious error)
1973 handle_service_request_multipart (void *cls,
1974 struct GNUNET_MESH_Tunnel * tunnel,
1976 const struct GNUNET_MessageHeader * message)
1978 return GNUNET_SYSERR;
1982 * Handle a request from another service to calculate a scalarproduct with us.
1984 * @param cls closure (set from #GNUNET_MESH_connect)
1985 * @param tunnel connection to the other end
1986 * @param tunnel_ctx place to store local state associated with the tunnel
1987 * @param sender who sent the message
1988 * @param message the actual message
1989 * @param atsi performance data for the connection
1990 * @return #GNUNET_OK to keep the connection open,
1991 * #GNUNET_SYSERR to close it (signal serious error)
1994 handle_service_request (void *cls,
1995 struct GNUNET_MESH_Tunnel * tunnel,
1997 const struct GNUNET_MessageHeader * message)
1999 struct ServiceSession * session;
2000 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2001 uint32_t mask_length;
2003 uint32_t used_elements;
2004 uint32_t element_count;
2005 uint32_t msg_length;
2006 unsigned char * current;
2007 struct ServiceSession * responder_session;
2009 enum SessionState needed_state;
2011 session = (struct ServiceSession *) * tunnel_ctx;
2012 if (BOB != session->role)
2014 GNUNET_break_op (0);
2015 return GNUNET_SYSERR;
2017 // is this tunnel already in use?
2018 if ((session->next) || (from_service_head == session))
2020 GNUNET_break_op (0);
2021 return GNUNET_SYSERR;
2023 // Check if message was sent by me, which would be bad!
2024 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
2026 GNUNET_free (session);
2028 return GNUNET_SYSERR;
2031 //we need at least a peer and one message id to compare
2032 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request))
2034 GNUNET_free (session);
2035 GNUNET_break_op (0);
2036 return GNUNET_SYSERR;
2038 mask_length = ntohl (msg->mask_length);
2039 pk_length = ntohl (msg->pk_length);
2040 used_elements = ntohl (msg->contained_element_count);
2041 element_count = ntohl (msg->element_count);
2042 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2043 +mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
2045 //sanity check: is the message as long as the message_count fields suggests?
2046 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements)
2047 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2050 GNUNET_free (session);
2051 GNUNET_break_op (0);
2052 return GNUNET_SYSERR;
2054 if (find_matching_session (from_service_tail,
2060 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2061 GNUNET_free (session);
2062 return GNUNET_SYSERR;
2065 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2066 session->state = SERVICE_REQUEST_RECEIVED;
2067 session->element_count = ntohl (msg->element_count);
2068 session->used_element_count = used_elements;
2069 session->tunnel = tunnel;
2072 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2073 current = (unsigned char *) &msg[1];
2074 //preserve the mask, we will need that later on
2075 session->mask = GNUNET_malloc (mask_length);
2076 memcpy (session->mask, current, mask_length);
2078 current += mask_length;
2080 //convert the publickey to sexp
2081 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))
2083 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
2084 GNUNET_free (session->mask);
2085 GNUNET_free (session);
2086 return GNUNET_SYSERR;
2089 current += pk_length;
2091 //check if service queue contains a matching request
2092 needed_state = CLIENT_RESPONSE_RECEIVED;
2093 responder_session = find_matching_session (from_client_tail,
2095 session->element_count,
2096 &needed_state, NULL);
2098 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2100 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2103 + used_elements * PAILLIER_ELEMENT_LENGTH)
2105 gcry_error_t ret = 0;
2106 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2107 // Convert each vector element to MPI_value
2108 for (i = 0; i < used_elements; i++)
2112 ret = gcry_mpi_scan (&session->a[i],
2114 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2115 PAILLIER_ELEMENT_LENGTH,
2119 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
2120 i, gcry_strsource (ret), gcry_strerror (ret));
2124 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2125 if (responder_session)
2127 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2128 if (GNUNET_OK != compute_service_response (session, responder_session))
2130 //something went wrong, remove it again...
2131 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2136 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2142 // TODO FEATURE: fallback to fragmentation, in case the message is too long
2143 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
2147 for (i = 0; i < used_elements; i++)
2149 gcry_mpi_release (session->a[i]);
2150 gcry_sexp_release (session->remote_pubkey);
2151 session->remote_pubkey = NULL;
2152 GNUNET_free_non_null (session->a);
2154 free_session (session);
2155 // and notify our client-session that we could not complete the session
2156 if (responder_session)
2157 // we just found the responder session in this queue
2158 responder_session->client_notification_task =
2159 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2161 return GNUNET_SYSERR;
2166 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2168 * @param cls closure (set from #GNUNET_MESH_connect)
2169 * @param tunnel connection to the other end
2170 * @param tunnel_ctx place to store local state associated with the tunnel
2171 * @param sender who sent the message
2172 * @param message the actual message
2173 * @param atsi performance data for the connection
2174 * @return #GNUNET_OK to keep the connection open,
2175 * #GNUNET_SYSERR to close it (signal serious error)
2178 handle_service_response_multipart (void *cls,
2179 struct GNUNET_MESH_Tunnel * tunnel,
2181 const struct GNUNET_MessageHeader * message)
2183 return GNUNET_SYSERR;
2187 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2189 * @param cls closure (set from #GNUNET_MESH_connect)
2190 * @param tunnel connection to the other end
2191 * @param tunnel_ctx place to store local state associated with the tunnel
2192 * @param sender who sent the message
2193 * @param message the actual message
2194 * @param atsi performance data for the connection
2195 * @return #GNUNET_OK to keep the connection open,
2196 * #GNUNET_SYSERR to close it (we are done)
2199 handle_service_response (void *cls,
2200 struct GNUNET_MESH_Tunnel * tunnel,
2202 const struct GNUNET_MessageHeader * message)
2204 struct ServiceSession * session;
2205 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2206 unsigned char * current;
2208 gcry_mpi_t s = NULL;
2209 gcry_mpi_t s_prime = NULL;
2212 uint32_t contained_element_count;
2214 gcry_mpi_t * r = NULL;
2215 gcry_mpi_t * r_prime = NULL;
2218 GNUNET_assert (NULL != message);
2219 session = (struct ServiceSession *) * tunnel_ctx;
2220 if (ALICE != session->role)
2222 GNUNET_break_op (0);
2223 return GNUNET_SYSERR;
2226 count = session->used_element_count;
2227 session->product = NULL;
2228 session->state = SERVICE_RESPONSE_RECEIVED;
2230 //we need at least a peer and one message id to compare
2231 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size))
2233 GNUNET_break_op (0);
2236 contained_element_count = ntohl (msg->contained_element_count);
2237 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2238 + 2 * contained_element_count * PAILLIER_ELEMENT_LENGTH
2239 + 2 * PAILLIER_ELEMENT_LENGTH;
2240 //sanity check: is the message as long as the message_count fields suggests?
2241 if ((ntohs (msg->header.size) != msg_size) || (count != contained_element_count))
2243 GNUNET_break_op (0);
2248 current = (unsigned char *) &msg[1];
2249 if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current,
2250 PAILLIER_ELEMENT_LENGTH, &read)))
2252 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2253 GNUNET_break_op (0);
2256 current += PAILLIER_ELEMENT_LENGTH;
2258 if (0 != (rc = gcry_mpi_scan (&s_prime, GCRYMPI_FMT_USG, current,
2259 PAILLIER_ELEMENT_LENGTH, &read)))
2261 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2262 GNUNET_break_op (0);
2265 current += PAILLIER_ELEMENT_LENGTH;
2267 r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2268 // Convert each kp[] to its MPI_value
2269 for (i = 0; i < count; i++)
2271 if (0 != (rc = gcry_mpi_scan (&r[i], GCRYMPI_FMT_USG, current,
2272 PAILLIER_ELEMENT_LENGTH, &read)))
2274 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2275 GNUNET_break_op (0);
2278 current += PAILLIER_ELEMENT_LENGTH;
2282 r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2283 // Convert each kq[] to its MPI_value
2284 for (i = 0; i < count; i++)
2286 if (0 != (rc = gcry_mpi_scan (&r_prime[i], GCRYMPI_FMT_USG, current,
2287 PAILLIER_ELEMENT_LENGTH, &read)))
2289 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2290 GNUNET_break_op (0);
2293 current += PAILLIER_ELEMENT_LENGTH;
2295 session->product = compute_scalar_product (session, r, r_prime, s, s_prime);
2299 gcry_mpi_release (s);
2301 gcry_mpi_release (s_prime);
2302 for (i = 0; r && i < count; i++)
2303 if (r[i]) gcry_mpi_release (r[i]);
2304 for (i = 0; r_prime && i < count; i++)
2305 if (r_prime[i]) gcry_mpi_release (r_prime[i]);
2306 GNUNET_free_non_null (r);
2307 GNUNET_free_non_null (r_prime);
2309 session->tunnel = NULL;
2310 // send message with product to client
2311 session->client_notification_task =
2312 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2314 // the tunnel has done its job, terminate our connection and the tunnel
2315 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2316 // just close the connection, as recommended by Christian
2317 return GNUNET_SYSERR;
2322 * Task run during shutdown.
2328 shutdown_task (void *cls,
2329 const struct GNUNET_SCHEDULER_TaskContext *tc)
2331 struct ServiceSession * session;
2332 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2334 do_shutdown = GNUNET_YES;
2336 // terminate all owned open tunnels.
2337 for (session = from_client_head; NULL != session; session = session->next)
2339 if ((FINALIZED != session->state) && (NULL != session->tunnel)){
2340 GNUNET_MESH_tunnel_destroy (session->tunnel);
2341 session->tunnel = NULL;
2343 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task)
2345 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2346 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2348 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task)
2350 GNUNET_SCHEDULER_cancel (session->service_request_task);
2351 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2353 if (NULL != session->client)
2355 GNUNET_SERVER_client_disconnect (session->client);
2356 session->client = NULL;
2359 for (session = from_service_head; NULL != session; session = session->next)
2360 if (NULL != session->tunnel){
2361 GNUNET_MESH_tunnel_destroy (session->tunnel);
2362 session->tunnel = NULL;
2367 GNUNET_MESH_disconnect (my_mesh);
2374 * Initialization of the program and message handlers
2376 * @param cls closure
2377 * @param server the initialized server
2378 * @param c configuration to use
2382 struct GNUNET_SERVER_Handle *server,
2383 const struct GNUNET_CONFIGURATION_Handle *c)
2385 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2386 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2387 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2390 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2391 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2392 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2393 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2394 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2397 static const uint32_t ports[] = {
2398 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2401 //generate private/public key set
2402 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2404 // register server callbacks and disconnect handler
2405 GNUNET_SERVER_add_handlers (server, server_handlers);
2406 GNUNET_SERVER_disconnect_notify (server,
2407 &handle_client_disconnect,
2409 GNUNET_break (GNUNET_OK ==
2410 GNUNET_CRYPTO_get_peer_identity (c,
2412 my_mesh = GNUNET_MESH_connect (c, NULL,
2413 &tunnel_incoming_handler,
2414 &tunnel_destruction_handler,
2415 mesh_handlers, ports);
2418 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2419 GNUNET_SCHEDULER_shutdown ();
2422 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2423 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2430 * The main function for the scalarproduct service.
2432 * @param argc number of arguments from the command line
2433 * @param argv command line arguments
2434 * @return 0 ok, 1 on error
2437 main (int argc, char *const *argv)
2439 return (GNUNET_OK ==
2440 GNUNET_SERVICE_run (argc, argv,
2442 GNUNET_SERVICE_OPTION_NONE,
2443 &run, NULL)) ? 0 : 1;
2446 /* end of gnunet-service-ext.c */