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;
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;
207 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
209 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
212 ///////////////////////////////////////////////////////////////////////////////
214 ///////////////////////////////////////////////////////////////////////////////
218 * Handle to the core service (NULL until we've connected to it).
220 static struct GNUNET_MESH_Handle *my_mesh;
223 * The identity of this host.
225 static struct GNUNET_PeerIdentity me;
228 * Service's own public key represented as string
230 static unsigned char * my_pubkey_external;
233 * Service's own public key represented as string
235 static uint32_t my_pubkey_external_length = 0;
240 static gcry_mpi_t my_n;
243 * Service's own n^2 (kept for performance)
245 static gcry_mpi_t my_nsquare;
248 * Service's own public exponent
250 static gcry_mpi_t my_g;
253 * Service's own private multiplier
255 static gcry_mpi_t my_mu;
258 * Service's own private exponent
260 static gcry_mpi_t my_lambda;
263 * Service's offset for values that could possibly be negative but are plaintext for encryption.
265 static gcry_mpi_t my_offset;
268 * Head of our double linked list for client-requests sent to us.
269 * for all of these elements we calculate a scalar product with a remote peer
270 * split between service->service and client->service for simplicity
272 static struct ServiceSession * from_client_head;
274 * Tail 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_tail;
281 * Head of our double linked list for service-requests sent to us.
282 * for all of these elements we help the requesting service in calculating a scalar product
283 * split between service->service and client->service for simplicity
285 static struct ServiceSession * from_service_head;
288 * Tail of our double linked list for service-requests sent to us.
289 * for all of these elements we help the requesting service in calculating a scalar product
290 * split between service->service and client->service for simplicity
292 static struct ServiceSession * from_service_tail;
295 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
297 static int do_shutdown;
299 ///////////////////////////////////////////////////////////////////////////////
301 ///////////////////////////////////////////////////////////////////////////////
304 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
309 gcry_sexp_t gen_params;
311 gcry_sexp_t tmp_sexp;
320 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
321 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
322 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
325 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
326 gcry_sexp_release (gen_params);
328 // get n and d of our publickey as MPI
329 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
330 GNUNET_assert (tmp_sexp);
331 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
332 gcry_sexp_release (tmp_sexp);
333 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
334 GNUNET_assert (tmp_sexp);
335 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
336 gcry_sexp_release (tmp_sexp);
337 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
338 GNUNET_assert (tmp_sexp);
339 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
340 gcry_sexp_release (key);
342 tmp1 = gcry_mpi_new (0);
343 tmp2 = gcry_mpi_new (0);
344 gcd = gcry_mpi_new (0);
345 my_g = gcry_mpi_new (0);
346 my_mu = gcry_mpi_new (0);
347 my_nsquare = gcry_mpi_new (0);
348 my_lambda = gcry_mpi_new (0);
351 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
352 gcry_mpi_sub_ui (tmp1, p, 1);
353 gcry_mpi_sub_ui (tmp2, q, 1);
354 gcry_mpi_gcd (gcd, tmp1, tmp2);
355 gcry_mpi_set (my_lambda, tmp1);
356 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
357 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
360 gcry_mpi_mul (my_nsquare, my_n, my_n);
364 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
365 // g must be smaller than n^2
366 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
369 // g must have gcd == 1 with n^2
370 gcry_mpi_gcd (gcd, my_g, my_nsquare);
372 while (gcry_mpi_cmp_ui (gcd, 1));
374 // is this a valid g?
375 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
376 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
377 gcry_mpi_sub_ui (tmp1, tmp1, 1);
378 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
379 gcry_mpi_gcd (gcd, tmp1, my_n);
381 while (gcry_mpi_cmp_ui (gcd, 1));
383 // calculate our mu based on g and n.
384 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
385 gcry_mpi_invm (my_mu, tmp1, my_n);
387 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
388 "(public-key (paillier (n %M)(g %M)))",
391 // get the length of this sexpression
392 my_pubkey_external_length = gcry_sexp_sprint (key,
397 GNUNET_assert (my_pubkey_external_length > 0);
398 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
400 // convert the sexpression to canonical format
401 gcry_sexp_sprint (key,
404 my_pubkey_external_length);
406 gcry_sexp_release (key);
408 // offset has to be sufficiently small to allow computation of:
409 // m1+m2 mod n == (S + a) + (S + b) mod n,
410 // if we have more complex operations, this factor needs to be lowered
411 my_offset = gcry_mpi_new (KEYBITS / 3);
412 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
418 * If target != size, move target bytes to the
419 * end of the size-sized buffer and zero out the
420 * first target-size bytes.
422 * @param buf original buffer
423 * @param size number of bytes in the buffer
424 * @param target target size of the buffer
427 adjust (unsigned char *buf, size_t size, size_t target)
430 memmove (&buf[target - size], buf, size);
431 memset (buf, 0, target - size);
436 * encrypts an element using the paillier crypto system
438 * @param c ciphertext (output)
440 * @param g the public base
441 * @param n the module from which which r is chosen (Z*_n)
442 * @param n_square the module for encryption, for performance reasons.
445 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
449 GNUNET_assert (tmp = gcry_mpi_new (0));
451 while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
452 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
453 // r must be 1 < r < n
456 gcry_mpi_powm (c, g, m, n_square);
457 gcry_mpi_powm (tmp, tmp, n, n_square);
458 gcry_mpi_mulm (c, tmp, c, n_square);
460 gcry_mpi_release (tmp);
464 * decrypts an element using the paillier crypto system
466 * @param m plaintext (output)
467 * @param c the ciphertext
468 * @param mu the modifier to correct encryption
469 * @param lambda the private exponent
470 * @param n the outer module for decryption
471 * @param n_square the inner module for decryption
474 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)
476 gcry_mpi_powm (m, c, lambda, n_square);
477 gcry_mpi_sub_ui (m, m, 1);
478 gcry_mpi_div (m, NULL, m, n, 0);
479 gcry_mpi_mulm (m, m, mu, n);
483 * computes the square sum over a vector of a given length.
485 * @param vector the vector to encrypt
486 * @param length the length of the vector
487 * @return an MPI value containing the calculated sum, never NULL
490 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
496 GNUNET_assert (sum = gcry_mpi_new (0));
497 GNUNET_assert (elem = gcry_mpi_new (0));
499 // calculare E(sum (ai ^ 2), publickey)
500 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) {
536 memcpy (buf, session->msg, size);
540 switch (ntohs (session->msg->type))
542 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
543 session->state = FINALIZED;
544 session->client_transmit_handle = NULL;
546 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
547 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
549 session->service_transmit_handle = NULL;
550 // reset flags for sending
551 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
552 prepare_service_request_multipart (session, NULL);
553 //TODO we have sent a message and now need to trigger trigger the next multipart message sending
555 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
556 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
558 session->service_transmit_handle = NULL;
559 if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
560 prepare_service_response_multipart (session, NULL);
563 session->service_transmit_handle = NULL;
566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567 "Sent a message of type %hu.\n",
568 ntohs (session->msg->type));
569 GNUNET_free (session->msg);
576 * initializes a new vector with fresh MPI values (=0) of a given length
578 * @param length of the vector to create
579 * @return the initialized vector, never NULL
582 initialize_mpi_vector (uint32_t length)
585 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
587 for (i = 0; i < length; i++)
588 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
593 * permutes an MPI vector according to the given permutation vector
595 * @param vector the vector to permuted
596 * @param perm the permutation to use
597 * @param length the length of the vectors
598 * @return the permuted vector (same as input), never NULL
601 permute_vector (gcry_mpi_t * vector,
605 gcry_mpi_t tmp[length];
608 GNUNET_assert (length > 0);
611 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
613 // permute vector according to given
614 for (i = 0; i < length; i++)
615 vector[i] = tmp[perm[i]];
621 * Populate a vector with random integer values and convert them to
623 * @param length the length of the vector we must generate
624 * @return an array of MPI values with random values
627 generate_random_vector (uint32_t length)
629 gcry_mpi_t * random_vector;
633 random_vector = initialize_mpi_vector (length);
634 for (i = 0; i < length; i++) {
635 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
637 // long to gcry_mpi_t
639 gcry_mpi_sub_ui (random_vector[i],
643 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
646 return random_vector;
650 * Finds a not terminated client/service session in the
651 * given DLL based on session key, element count and state.
653 * @param tail - the tail of the DLL
654 * @param my - the session to compare it to
655 * @return a pointer to a matching session,
658 static struct ServiceSession *
659 find_matching_session (struct ServiceSession * tail,
660 const struct GNUNET_HashCode * key,
661 uint32_t element_count,
662 enum SessionState * state,
663 const struct GNUNET_PeerIdentity * peerid)
665 struct ServiceSession * curr;
667 for (curr = tail; NULL != curr; curr = curr->prev) {
668 // if the key matches, and the element_count is same
669 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
670 && (curr->element_count == element_count)) {
671 // if incoming state is NULL OR is same as state of the queued request
672 if ((NULL == state) || (curr->state == *state)) {
673 // if peerid is NULL OR same as the peer Id in the queued request
675 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
676 // matches and is not an already terminated session
686 free_session (struct ServiceSession * session)
691 for (i = 0; i < session->used_element_count; i++)
692 gcry_mpi_release (session->a[i]);
694 GNUNET_free (session->a);
696 if (session->product)
697 gcry_mpi_release (session->product);
699 if (session->remote_pubkey)
700 gcry_sexp_release (session->remote_pubkey);
702 GNUNET_free_non_null (session->vector);
703 GNUNET_free (session);
705 ///////////////////////////////////////////////////////////////////////////////
706 // Event and Message Handlers
707 ///////////////////////////////////////////////////////////////////////////////
710 * A client disconnected.
712 * Remove the associated session(s), release datastructures
713 * and cancel pending outgoing transmissions to the client.
714 * if the session has not yet completed, we also cancel Alice's request to Bob.
716 * @param cls closure, NULL
717 * @param client identification of the client
720 handle_client_disconnect (void *cls,
721 struct GNUNET_SERVER_Client *client)
723 struct ServiceSession *session;
727 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731 _ ("Client (%p) disconnected from us.\n"), client);
732 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
734 if (!(session->role == BOB && session->state == FINALIZED)) {
735 //we MUST terminate any client message underway
736 if (session->service_transmit_handle && session->tunnel)
737 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
738 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
739 GNUNET_MESH_tunnel_destroy (session->tunnel);
741 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
742 GNUNET_SCHEDULER_cancel (session->client_notification_task);
743 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
745 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
746 GNUNET_SCHEDULER_cancel (session->service_request_task);
747 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
749 if (NULL != session->client_transmit_handle) {
750 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
751 session->client_transmit_handle = NULL;
753 free_session (session);
757 * Notify the client that the session has succeeded or failed completely.
758 * This message gets sent to
759 * * alice's client if bob disconnected or to
760 * * bob's client if the operation completed or alice disconnected
762 * @param client_session the associated client session
763 * @return GNUNET_NO, if we could not notify the client
764 * GNUNET_YES if we notified it.
767 prepare_client_end_notification (void * cls,
768 const struct GNUNET_SCHEDULER_TaskContext * tc)
770 struct ServiceSession * session = cls;
771 struct GNUNET_SCALARPRODUCT_client_response * msg;
773 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
775 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
776 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
777 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
778 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
779 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
780 // signal error if not signalized, positive result-range field but zero length.
781 msg->product_length = htonl (0);
782 msg->range = (session->state == FINALIZED) ? 0 : -1;
784 session->msg = &msg->header;
786 //transmit this message to our client
787 session->client_transmit_handle =
788 GNUNET_SERVER_notify_transmit_ready (session->client,
789 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
790 GNUNET_TIME_UNIT_FOREVER_REL,
794 // if we could not even queue our request, something is wrong
795 if (NULL == session->client_transmit_handle) {
796 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
797 // usually gets freed by do_send_message
802 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
807 prepare_service_response_multipart (void *cls,
808 const struct GNUNET_SCHEDULER_TaskContext *tc)
810 struct ServiceSession * session = cls;
811 unsigned char * current;
812 unsigned char * element_exported;
813 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
817 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
819 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
820 todo_count = session->used_element_count - session->transferred_element_count;
822 if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
823 // send the currently possible maximum chunk, we always transfer both permutations
824 todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
826 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
827 msg = GNUNET_malloc (msg_length);
828 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
829 msg->header.size = htons (msg_length);
830 msg->multipart_element_count = htonl (todo_count);
832 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
833 current = (unsigned char *) &msg[1];
835 for (i = session->transferred_element_count; i < session->transferred_element_count + todo_count; i++) {
837 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
838 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
839 element_exported, PAILLIER_ELEMENT_LENGTH,
842 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
843 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
844 current += PAILLIER_ELEMENT_LENGTH;
846 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
847 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
848 element_exported, PAILLIER_ELEMENT_LENGTH,
850 session->r_prime[i]));
851 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
852 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
853 current += PAILLIER_ELEMENT_LENGTH;
855 GNUNET_free (element_exported);
856 for (i = session->transferred_element_count; i < session->transferred_element_count; i++) {
857 gcry_mpi_release (session->r_prime[i]);
858 gcry_mpi_release (session->r[i]);
860 session->transferred_element_count += todo_count;
861 session->msg = (struct GNUNET_MessageHeader *) msg;
862 session->service_transmit_handle =
863 GNUNET_MESH_notify_transmit_ready (session->tunnel,
865 GNUNET_TIME_UNIT_FOREVER_REL,
869 //disconnect our client
870 if (NULL == session->service_transmit_handle) {
871 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
872 session->state = FINALIZED;
874 session->response->client_notification_task =
875 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
879 if (session->transferred_element_count != session->used_element_count)
881 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
884 session->state = FINALIZED;
889 * generates the response message to be sent to alice after computing
890 * the values (1), (2), S and S'
891 * (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)})$
892 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
893 * S: $S := E_A(sum (r_i + b_i)^2)$
894 * S': $S' := E_A(sum r_i^2)$
896 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
897 * @param s_prime S': $S' := E_A(sum r_i^2)$
898 * @param session the associated requesting session with alice
899 * @return GNUNET_NO if we could not send our message
900 * GNUNET_OK if the operation succeeded
903 prepare_service_response (gcry_mpi_t s,
905 struct ServiceSession * session)
907 struct GNUNET_SCALARPRODUCT_service_response * msg;
908 uint32_t msg_length = 0;
909 unsigned char * current = NULL;
910 unsigned char * element_exported = NULL;
911 size_t element_length = 0;
914 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
915 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
917 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH) { //kp, kq
918 msg_length += +2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH;
919 session->transferred_element_count = session->used_element_count;
922 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
925 msg = GNUNET_malloc (msg_length);
927 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
928 msg->header.size = htons (msg_length);
929 msg->total_element_count = htonl (session->element_count);
930 msg->contained_element_count = htonl (session->used_element_count);
931 msg->contained_element_count = htonl (session->transferred_element_count);
932 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
933 current = (unsigned char *) &msg[1];
935 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
936 // 4 times the same logics with slight variations.
937 // doesn't really justify having 2 functions for that
938 // so i put it into blocks to enhance readability
940 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
941 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
942 element_exported, PAILLIER_ELEMENT_LENGTH,
945 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
946 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
947 current += PAILLIER_ELEMENT_LENGTH;
950 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
951 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
952 element_exported, PAILLIER_ELEMENT_LENGTH,
955 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
956 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
957 current += PAILLIER_ELEMENT_LENGTH;
960 for (i = 0; i < session->transferred_element_count; i++) {
962 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
963 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
964 element_exported, PAILLIER_ELEMENT_LENGTH,
967 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
968 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
969 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,
975 session->r_prime[i]));
976 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
977 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
978 current += PAILLIER_ELEMENT_LENGTH;
981 GNUNET_free (element_exported);
982 for (i = 0; i < session->transferred_element_count; i++) {
983 gcry_mpi_release (session->r_prime[i]);
984 gcry_mpi_release (session->r[i]);
986 gcry_mpi_release (s);
987 gcry_mpi_release (s_prime);
989 session->msg = (struct GNUNET_MessageHeader *) msg;
990 session->service_transmit_handle =
991 GNUNET_MESH_notify_transmit_ready (session->tunnel,
993 GNUNET_TIME_UNIT_FOREVER_REL,
997 //disconnect our client
998 if (NULL == session->service_transmit_handle) {
999 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1000 session->state = FINALIZED;
1002 session->response->client_notification_task =
1003 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1007 if (session->transferred_element_count != session->used_element_count)
1009 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1012 session->state = FINALIZED;
1019 * compute the values
1020 * (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)})$
1021 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1022 * S: $S := E_A(\sum (r_i + b_i)^2)$
1023 * S': $S' := E_A(\sum r_i^2)$
1025 * @param request the requesting session + bob's requesting peer
1026 * @param response the responding session + bob's client handle
1027 * @return GNUNET_SYSERR if the computation failed
1028 * GNUNET_OK if everything went well.
1031 compute_service_response (struct ServiceSession * request,
1032 struct ServiceSession * response)
1036 int ret = GNUNET_SYSERR;
1040 gcry_mpi_t * rand = NULL;
1041 gcry_mpi_t * r = NULL;
1042 gcry_mpi_t * r_prime = NULL;
1045 gcry_mpi_t * a_pi_prime;
1047 gcry_mpi_t * rand_pi;
1048 gcry_mpi_t * rand_pi_prime;
1049 gcry_mpi_t s = NULL;
1050 gcry_mpi_t s_prime = NULL;
1051 gcry_mpi_t remote_n = NULL;
1052 gcry_mpi_t remote_nsquare;
1053 gcry_mpi_t remote_g = NULL;
1054 gcry_sexp_t tmp_exp;
1057 count = request->used_element_count;
1059 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1060 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1061 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1062 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1063 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1064 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1066 // convert responder session to from long to mpi
1067 for (i = 0, j = 0; i < response->element_count && j < count; i++) {
1068 if (request->mask[i / 8] & (1 << (i % 8))) {
1069 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1070 // long to gcry_mpi_t
1071 if (0 > response->vector[i]) {
1072 b[j] = gcry_mpi_new (0);
1073 gcry_mpi_sub_ui (b[j], b[j], value);
1076 b[j] = gcry_mpi_set_ui (NULL, value);
1081 GNUNET_free (response->vector);
1082 response->vector = NULL;
1084 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1086 GNUNET_break_op (0);
1087 gcry_sexp_release (request->remote_pubkey);
1088 request->remote_pubkey = NULL;
1091 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1094 gcry_sexp_release (tmp_exp);
1097 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1098 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1099 gcry_sexp_release (tmp_exp);
1100 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1101 gcry_sexp_release (request->remote_pubkey);
1102 request->remote_pubkey = NULL;
1104 GNUNET_break_op (0);
1105 gcry_mpi_release (remote_n);
1108 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1111 gcry_mpi_release (remote_n);
1112 gcry_sexp_release (tmp_exp);
1115 gcry_sexp_release (tmp_exp);
1117 // generate r, p and q
1118 rand = generate_random_vector (count);
1119 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1120 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1121 //initialize the result vectors
1122 r = initialize_mpi_vector (count);
1123 r_prime = initialize_mpi_vector (count);
1125 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1126 // those values, thus we can work with the references
1127 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1128 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1129 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1130 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1131 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1133 // generate p and q permutations for a, b and r
1134 GNUNET_assert (permute_vector (a_pi, p, count));
1135 GNUNET_assert (permute_vector (b_pi, p, count));
1136 GNUNET_assert (permute_vector (rand_pi, p, count));
1137 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1138 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1140 // encrypt the element
1141 // for the sake of readability I decided to have dedicated permutation
1142 // vectors, which get rid of all the lookups in p/q.
1143 // however, ap/aq are not absolutely necessary but are just abstraction
1144 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1145 for (i = 0; i < count; i++) {
1146 // E(S - r_pi - b_pi)
1147 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1148 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1149 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1151 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1152 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1156 GNUNET_free (rand_pi);
1158 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1159 for (i = 0; i < count; i++) {
1161 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1162 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1164 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1165 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1167 GNUNET_free (a_pi_prime);
1168 GNUNET_free (rand_pi_prime);
1171 request->r_prime = r_prime;
1172 request->response = response;
1174 // Calculate S' = E(SUM( r_i^2 ))
1175 s_prime = compute_square_sum (rand, count);
1176 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1178 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1179 for (i = 0; i < count; i++) {
1180 gcry_mpi_add (rand[i], rand[i], b[i]);
1182 s = compute_square_sum (rand, count);
1183 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1184 gcry_mpi_release (remote_n);
1185 gcry_mpi_release (remote_g);
1186 gcry_mpi_release (remote_nsquare);
1188 // release r and tmp
1189 for (i = 0; i < count; i++)
1190 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1191 gcry_mpi_release (rand[i]);
1193 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1194 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1195 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1196 GNUNET_i2s (&request->peer));
1201 for (i = 0; i < count; i++) {
1202 gcry_mpi_release (b[i]);
1203 gcry_mpi_release (request->a[i]);
1207 GNUNET_free (request->a);
1214 prepare_service_request_multipart (void *cls,
1215 const struct GNUNET_SCHEDULER_TaskContext *tc)
1217 struct ServiceSession * session = cls;
1218 unsigned char * current;
1219 unsigned char * element_exported;
1220 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1223 uint32_t msg_length;
1224 uint32_t todo_count;
1225 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1229 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1230 todo_count = session->used_element_count - session->transferred_element_count;
1232 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1233 // send the currently possible maximum chunk
1234 todo_count = MULTIPART_ELEMENT_CAPACITY;
1236 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1237 msg = GNUNET_malloc (msg_length);
1238 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1239 msg->header.size = htons (msg_length);
1240 msg->multipart_element_count = htonl (todo_count);
1242 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1243 a = gcry_mpi_new (KEYBITS * 2);
1244 current = (unsigned char *) &msg[1];
1245 // encrypt our vector and generate string representations
1246 for (i = session->last_processed_element, j = 0; i < session->element_count; i++) {
1247 // is this a used element?
1248 if (session->mask[i / 8] & 1 << (i % 8)) {
1249 if (todo_count <= j)
1250 break; //reached end of this message, can't include more
1252 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1253 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1255 a = gcry_mpi_set_ui (a, 0);
1256 // long to gcry_mpi_t
1257 if (session->vector[i] < 0)
1258 gcry_mpi_sub_ui (a, a, value);
1260 gcry_mpi_add_ui (a, a, value);
1262 session->a[session->transferred_element_count + j++] = gcry_mpi_set (NULL, a);
1263 gcry_mpi_add (a, a, my_offset);
1264 encrypt_element (a, a, my_g, my_n, my_nsquare);
1266 // get representation as string
1267 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1268 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1269 element_exported, PAILLIER_ELEMENT_LENGTH,
1273 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1274 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1276 // copy over to the message
1277 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1278 current += PAILLIER_ELEMENT_LENGTH;
1281 gcry_mpi_release (a);
1282 GNUNET_free (element_exported);
1283 session->transferred_element_count += todo_count;
1285 session->msg = (struct GNUNET_MessageHeader *) msg;
1286 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1288 //transmit via mesh messaging
1289 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1290 GNUNET_TIME_UNIT_FOREVER_REL,
1294 if (!session->service_transmit_handle) {
1295 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1297 session->msg = NULL;
1298 session->client_notification_task =
1299 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1303 if (session->transferred_element_count != session->used_element_count) {
1304 session->last_processed_element = i;
1308 session->state = WAITING_FOR_SERVICE_RESPONSE;
1312 * Executed by Alice, fills in a service-request message and sends it to the given peer
1314 * @param session the session associated with this request, then also holds the CORE-handle
1315 * @return #GNUNET_SYSERR if we could not send the message
1316 * #GNUNET_NO if the message was too large
1317 * #GNUNET_OK if we sent it
1320 prepare_service_request (void *cls,
1321 const struct GNUNET_SCHEDULER_TaskContext *tc)
1323 struct ServiceSession * session = cls;
1324 unsigned char * current;
1325 unsigned char * element_exported;
1326 struct GNUNET_SCALARPRODUCT_service_request * msg;
1329 uint32_t msg_length;
1330 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1334 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1338 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1339 +session->mask_length
1340 + my_pubkey_external_length;
1342 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used_element_count * PAILLIER_ELEMENT_LENGTH) {
1343 msg_length += session->used_element_count * PAILLIER_ELEMENT_LENGTH;
1344 session->transferred_element_count = session->used_element_count;
1347 //create a multipart msg, first we calculate a new msg size for the head msg
1348 session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1351 msg = GNUNET_malloc (msg_length);
1352 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1353 msg->total_element_count = htonl (session->used_element_count);
1354 msg->contained_element_count = htonl (session->transferred_element_count);
1355 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1356 msg->mask_length = htonl (session->mask_length);
1357 msg->pk_length = htonl (my_pubkey_external_length);
1358 msg->element_count = htonl (session->element_count);
1359 msg->header.size = htons (msg_length);
1361 // fill in the payload
1362 current = (unsigned char *) &msg[1];
1363 // copy over the mask
1364 memcpy (current, session->mask, session->mask_length);
1365 // copy over our public key
1366 current += session->mask_length;
1367 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1368 current += my_pubkey_external_length;
1370 // now copy over the element vector
1371 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1372 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1373 a = gcry_mpi_new (KEYBITS * 2);
1374 // encrypt our vector and generate string representations
1375 for (i = 0, j = 0; i < session->element_count; i++) {
1376 // if this is a used element...
1377 if (session->mask[i / 8] & 1 << (i % 8)) {
1378 if (session->transferred_element_count <= j)
1379 break; //reached end of this message, can't include more
1381 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1382 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1384 a = gcry_mpi_set_ui (a, 0);
1385 // long to gcry_mpi_t
1386 if (session->vector[i] < 0)
1387 gcry_mpi_sub_ui (a, a, value);
1389 gcry_mpi_add_ui (a, a, value);
1391 session->a[j++] = gcry_mpi_set (NULL, a);
1392 gcry_mpi_add (a, a, my_offset);
1393 encrypt_element (a, a, my_g, my_n, my_nsquare);
1395 // get representation as string
1396 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1397 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1398 element_exported, PAILLIER_ELEMENT_LENGTH,
1402 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1403 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1405 // copy over to the message
1406 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1407 current += PAILLIER_ELEMENT_LENGTH;
1410 gcry_mpi_release (a);
1411 GNUNET_free (element_exported);
1413 session->msg = (struct GNUNET_MessageHeader *) msg;
1414 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1416 //transmit via mesh messaging
1417 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1418 GNUNET_TIME_UNIT_FOREVER_REL,
1422 if (!session->service_transmit_handle) {
1423 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1425 session->msg = NULL;
1426 session->client_notification_task =
1427 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1431 if (session->transferred_element_count != session->used_element_count) {
1432 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1433 session->last_processed_element = i;
1436 //singlepart message
1437 session->state = WAITING_FOR_SERVICE_RESPONSE;
1441 * Handler for a client request message.
1442 * Can either be type A or B
1443 * A: request-initiation to compute a scalar product with a peer
1444 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1446 * @param cls closure
1447 * @param client identification of the client
1448 * @param message the actual message
1451 handle_client_request (void *cls,
1452 struct GNUNET_SERVER_Client *client,
1453 const struct GNUNET_MessageHeader *message)
1455 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1456 struct ServiceSession * session;
1457 uint32_t element_count;
1458 uint32_t mask_length;
1463 // only one concurrent session per client connection allowed, simplifies logics a lot...
1464 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1465 if ((NULL != session) && (session->state != FINALIZED)) {
1466 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1469 else if (NULL != session) {
1470 // old session is already completed, clean it up
1471 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1472 free_session (session);
1475 //we need at least a peer and one message id to compare
1476 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1477 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1478 _ ("Too short message received from client!\n"));
1479 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1483 msg_type = ntohs (msg->header.type);
1484 element_count = ntohl (msg->element_count);
1485 mask_length = ntohl (msg->mask_length);
1487 //sanity check: is the message as long as the message_count fields suggests?
1488 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1489 || (0 == element_count)) {
1490 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1491 _ ("Invalid message received from client, session information incorrect!\n"));
1492 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1496 // do we have a duplicate session here already?
1497 if (NULL != find_matching_session (from_client_tail,
1501 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1502 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1503 GNUNET_h2s (&msg->key));
1504 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1508 session = GNUNET_new (struct ServiceSession);
1509 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1510 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1511 session->client = client;
1512 session->element_count = element_count;
1513 session->mask_length = mask_length;
1514 // get our transaction key
1515 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1516 //allocate memory for vector and encrypted vector
1517 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1518 vector = (int32_t *) & msg[1];
1520 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1523 GNUNET_h2s (&session->key));
1525 session->role = ALICE;
1527 session->mask = GNUNET_malloc (mask_length);
1528 memcpy (session->mask, &vector[element_count], mask_length);
1530 // copy over the elements
1531 session->used_element_count = 0;
1532 for (i = 0; i < element_count; i++) {
1533 session->vector[i] = ntohl (vector[i]);
1534 if (session->vector[i] == 0)
1535 session->mask[i / 8] &= ~(1 << (i % 8));
1536 if (session->mask[i / 8] & (1 << (i % 8)))
1537 session->used_element_count++;
1540 if (0 == session->used_element_count) {
1541 GNUNET_break_op (0);
1542 GNUNET_free (session->vector);
1543 GNUNET_free (session);
1544 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1547 //session with ourself makes no sense!
1548 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1550 GNUNET_free (session->vector);
1551 GNUNET_free (session);
1552 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1556 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1557 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1558 _ ("Creating new tunnel to for session with key %s.\n"),
1559 GNUNET_h2s (&session->key));
1560 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1562 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1565 //prepare_service_request, tunnel_peer_disconnect_handler,
1566 if (!session->tunnel) {
1568 GNUNET_free (session->vector);
1569 GNUNET_free (session);
1570 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1573 GNUNET_SERVER_client_set_user_context (client, session);
1574 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1576 session->state = CLIENT_REQUEST_RECEIVED;
1577 session->service_request_task =
1578 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1583 struct ServiceSession * requesting_session;
1584 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1586 session->role = BOB;
1587 session->mask = NULL;
1588 // copy over the elements
1589 session->used_element_count = element_count;
1590 for (i = 0; i < element_count; i++)
1591 session->vector[i] = ntohl (vector[i]);
1592 session->state = CLIENT_RESPONSE_RECEIVED;
1594 GNUNET_SERVER_client_set_user_context (client, session);
1595 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1597 //check if service queue contains a matching request
1598 requesting_session = find_matching_session (from_service_tail,
1600 session->element_count,
1601 &needed_state, NULL);
1602 if (NULL != requesting_session) {
1603 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));
1604 if (GNUNET_OK != compute_service_response (requesting_session, session))
1605 session->client_notification_task =
1606 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1611 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));
1612 // no matching session exists yet, store the response
1613 // for later processing by handle_service_request()
1616 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1620 * Function called for inbound tunnels.
1622 * @param cls closure
1623 * @param tunnel new handle to the tunnel
1624 * @param initiator peer that started the tunnel
1625 * @param atsi performance information for the tunnel
1626 * @return initial tunnel context for the tunnel
1627 * (can be NULL -- that's not an error)
1630 tunnel_incoming_handler (void *cls,
1631 struct GNUNET_MESH_Tunnel *tunnel,
1632 const struct GNUNET_PeerIdentity *initiator,
1635 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1637 c->peer = *initiator;
1640 c->state = WAITING_FOR_SERVICE_REQUEST;
1645 * Function called whenever a tunnel is destroyed. Should clean up
1646 * any associated state.
1648 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1650 * @param cls closure (set from GNUNET_MESH_connect)
1651 * @param tunnel connection to the other end (henceforth invalid)
1652 * @param tunnel_ctx place where local state associated
1653 * with the tunnel is stored
1656 tunnel_destruction_handler (void *cls,
1657 const struct GNUNET_MESH_Tunnel *tunnel,
1660 struct ServiceSession * session = tunnel_ctx;
1661 struct ServiceSession * client_session;
1662 struct ServiceSession * curr;
1664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1666 GNUNET_h2s (&session->key),
1667 GNUNET_i2s (&session->peer));
1668 if (ALICE == session->role) {
1669 // as we have only one peer connected in each session, just remove the session
1671 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1672 session->tunnel = NULL;
1673 // if this happened before we received the answer, we must terminate the session
1674 session->client_notification_task =
1675 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1679 else { //(BOB == session->role) service session
1680 // remove the session, unless it has already been dequeued, but somehow still active
1681 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1682 // scenario: disconnect before alice can send her message to bob.
1683 for (curr = from_service_head; NULL != curr; curr = curr->next)
1684 if (curr == session) {
1685 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1688 // there is a client waiting for this service session, terminate it, too!
1689 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1690 client_session = find_matching_session (from_client_tail,
1692 session->element_count,
1694 free_session (session);
1696 // the client has to check if it was waiting for a result
1697 // or if it was a responder, no point in adding more statefulness
1698 if (client_session && (!do_shutdown)) {
1699 client_session->state = FINALIZED;
1700 client_session->client_notification_task =
1701 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1708 * Compute our scalar product, done by Alice
1710 * @param session - the session associated with this computation
1711 * @param kp - (1) from the protocol definition:
1712 * $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)})$
1713 * @param kq - (2) from the protocol definition:
1714 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1715 * @param s - S from the protocol definition:
1716 * $S := E_A(\sum (r_i + b_i)^2)$
1717 * @param stick - S' from the protocol definition:
1718 * $S' := E_A(\sum r_i^2)$
1719 * @return product as MPI, never NULL
1722 compute_scalar_product (struct ServiceSession * session)
1733 count = session->used_element_count;
1734 tmp = gcry_mpi_new (KEYBITS);
1735 // due to the introduced static offset S, we now also have to remove this
1736 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1737 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1738 for (i = 0; i < count; i++) {
1739 decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1740 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1741 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1742 decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1743 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1744 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1747 // calculate t = sum(ai)
1748 t = compute_square_sum (session->a, count);
1751 u = gcry_mpi_new (0);
1752 tmp = compute_square_sum (session->r, count);
1753 gcry_mpi_sub (u, u, tmp);
1754 gcry_mpi_release (tmp);
1757 utick = gcry_mpi_new (0);
1758 tmp = compute_square_sum (session->r_prime, count);
1759 gcry_mpi_sub (utick, utick, tmp);
1761 GNUNET_assert (p = gcry_mpi_new (0));
1762 GNUNET_assert (ptick = gcry_mpi_new (0));
1765 decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1766 decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1769 gcry_mpi_add (p, session->s, t);
1770 gcry_mpi_add (p, p, u);
1773 gcry_mpi_add (ptick, session->s_prime, t);
1774 gcry_mpi_add (ptick, ptick, utick);
1776 gcry_mpi_release (t);
1777 gcry_mpi_release (u);
1778 gcry_mpi_release (utick);
1781 gcry_mpi_sub (p, p, ptick);
1782 gcry_mpi_release (ptick);
1783 tmp = gcry_mpi_set_ui (tmp, 2);
1784 gcry_mpi_div (p, NULL, p, tmp, 0);
1786 gcry_mpi_release (tmp);
1787 for (i = 0; i < count; i++)
1788 gcry_mpi_release (session->a[i]);
1789 GNUNET_free (session->a);
1796 * prepare the response we will send to alice or bobs' clients.
1797 * in Bobs case the product will be NULL.
1799 * @param session the session associated with our client.
1802 prepare_client_response (void *cls,
1803 const struct GNUNET_SCHEDULER_TaskContext *tc)
1805 struct ServiceSession * session = cls;
1806 struct GNUNET_SCALARPRODUCT_client_response * msg;
1807 unsigned char * product_exported = NULL;
1808 size_t product_length = 0;
1809 uint32_t msg_length = 0;
1814 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1816 if (session->product) {
1817 gcry_mpi_t value = gcry_mpi_new (0);
1819 sign = gcry_mpi_cmp_ui (session->product, 0);
1820 // libgcrypt can not handle a print of a negative number
1821 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1823 gcry_mpi_sub (value, value, session->product);
1825 else if (0 < sign) {
1827 gcry_mpi_add (value, value, session->product);
1832 gcry_mpi_release (session->product);
1833 session->product = NULL;
1835 // get representation as string
1837 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1841 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1843 range = -1; // signal error with product-length = 0 and range = -1
1845 gcry_mpi_release (value);
1848 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1849 msg = GNUNET_malloc (msg_length);
1850 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1851 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1852 if (product_exported != NULL) {
1853 memcpy (&msg[1], product_exported, product_length);
1854 GNUNET_free (product_exported);
1856 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1857 msg->header.size = htons (msg_length);
1859 msg->product_length = htonl (product_length);
1861 session->msg = (struct GNUNET_MessageHeader *) msg;
1862 //transmit this message to our client
1863 session->client_transmit_handle =
1864 GNUNET_SERVER_notify_transmit_ready (session->client,
1866 GNUNET_TIME_UNIT_FOREVER_REL,
1869 if (NULL == session->client_transmit_handle) {
1870 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1871 _ ("Could not send message to client (%p)!\n"),
1873 session->client = NULL;
1874 // callback was not called!
1876 session->msg = NULL;
1879 // gracefully sent message, just terminate session structure
1880 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1881 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1883 GNUNET_h2s (&session->key));
1887 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1889 * @param cls closure (set from #GNUNET_MESH_connect)
1890 * @param tunnel connection to the other end
1891 * @param tunnel_ctx place to store local state associated with the tunnel
1892 * @param sender who sent the message
1893 * @param message the actual message
1894 * @param atsi performance data for the connection
1895 * @return #GNUNET_OK to keep the connection open,
1896 * #GNUNET_SYSERR to close it (signal serious error)
1899 handle_service_request_multipart (void *cls,
1900 struct GNUNET_MESH_Tunnel * tunnel,
1902 const struct GNUNET_MessageHeader * message)
1904 struct ServiceSession * session;
1905 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1906 uint32_t used_elements;
1907 uint32_t contained_elements;
1908 uint32_t msg_length;
1909 unsigned char * current;
1910 struct ServiceSession * responder_session;
1913 // are we in the correct state?
1914 session = (struct ServiceSession *) * tunnel_ctx;
1915 if (BOB != session->role) {
1918 if (WAITING_FOR_MULTIPART_TRANSMISSION != session->state) {
1921 // shorter than minimum?
1922 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1925 used_elements = session->used_element_count;
1926 contained_elements = ntohl (msg->multipart_element_count);
1927 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1928 + contained_elements * PAILLIER_ELEMENT_LENGTH;
1930 if (( ntohs (msg->header.size) != msg_length)
1931 || (used_elements < contained_elements + session->transferred_element_count)) {
1934 current = (unsigned char *) &msg[1];
1935 if (contained_elements != 0) {
1936 gcry_error_t ret = 0;
1937 // Convert each vector element to MPI_value
1938 for (i = session->transferred_element_count; i < session->transferred_element_count+contained_elements; i++) {
1941 ret = gcry_mpi_scan (&session->a[i],
1943 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1944 PAILLIER_ELEMENT_LENGTH,
1947 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1948 i, gcry_strsource (ret), gcry_strerror (ret));
1952 session->transferred_element_count+=contained_elements;
1954 if (session->transferred_element_count == used_elements) {
1955 // single part finished
1956 session->state = SERVICE_REQUEST_RECEIVED;
1957 if (responder_session) {
1958 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1959 if (GNUNET_OK != compute_service_response (session, responder_session)) {
1960 //something went wrong, remove it again...
1961 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1966 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1969 // multipart message
1975 for (i = 0; i < session->transferred_element_count; i++)
1977 gcry_mpi_release (session->a[i]);
1978 gcry_sexp_release (session->remote_pubkey);
1979 session->remote_pubkey = NULL;
1980 GNUNET_free (session->a);
1982 free_session (session);
1983 // and notify our client-session that we could not complete the session
1984 if (session->response)
1985 // we just found the responder session in this queue
1986 session->response->client_notification_task =
1987 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1989 return GNUNET_SYSERR;
1993 * Handle a request from another service to calculate a scalarproduct with us.
1995 * @param cls closure (set from #GNUNET_MESH_connect)
1996 * @param tunnel connection to the other end
1997 * @param tunnel_ctx place to store local state associated with the tunnel
1998 * @param sender who sent the message
1999 * @param message the actual message
2000 * @param atsi performance data for the connection
2001 * @return #GNUNET_OK to keep the connection open,
2002 * #GNUNET_SYSERR to close it (signal serious error)
2005 handle_service_request (void *cls,
2006 struct GNUNET_MESH_Tunnel * tunnel,
2008 const struct GNUNET_MessageHeader * message)
2010 struct ServiceSession * session;
2011 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2012 uint32_t mask_length;
2014 uint32_t used_elements;
2015 uint32_t contained_elements;
2016 uint32_t element_count;
2017 uint32_t msg_length;
2018 unsigned char * current;
2020 enum SessionState needed_state;
2022 session = (struct ServiceSession *) * tunnel_ctx;
2023 if (BOB != session->role) {
2024 GNUNET_break_op (0);
2025 return GNUNET_SYSERR;
2027 // is this tunnel already in use?
2028 if ((session->next) || (from_service_head == session)) {
2029 GNUNET_break_op (0);
2030 return GNUNET_SYSERR;
2032 // Check if message was sent by me, which would be bad!
2033 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2034 GNUNET_free (session);
2036 return GNUNET_SYSERR;
2038 // shorter than expected?
2039 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2040 GNUNET_free (session);
2041 GNUNET_break_op (0);
2042 return GNUNET_SYSERR;
2044 mask_length = ntohl (msg->mask_length);
2045 pk_length = ntohl (msg->pk_length);
2046 used_elements = ntohl (msg->total_element_count);
2047 contained_elements = ntohl (msg->contained_element_count);
2048 element_count = ntohl (msg->element_count);
2049 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2050 +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2052 //sanity check: is the message as long as the message_count fields suggests?
2053 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2054 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2056 GNUNET_free (session);
2057 GNUNET_break_op (0);
2058 return GNUNET_SYSERR;
2060 if (find_matching_session (from_service_tail,
2065 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2066 GNUNET_free (session);
2067 return GNUNET_SYSERR;
2070 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2071 session->element_count = element_count;
2072 session->used_element_count = used_elements;
2073 session->transferred_element_count = contained_elements;
2074 session->tunnel = tunnel;
2077 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2078 current = (unsigned char *) &msg[1];
2079 //preserve the mask, we will need that later on
2080 session->mask = GNUNET_malloc (mask_length);
2081 memcpy (session->mask, current, mask_length);
2083 current += mask_length;
2085 //convert the publickey to sexp
2086 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1)) {
2087 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
2088 GNUNET_free (session->mask);
2089 GNUNET_free (session);
2090 return GNUNET_SYSERR;
2093 current += pk_length;
2095 //check if service queue contains a matching request
2096 needed_state = CLIENT_RESPONSE_RECEIVED;
2097 session->response = find_matching_session (from_client_tail,
2099 session->element_count,
2100 &needed_state, NULL);
2102 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2103 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2104 if (contained_elements != 0) {
2105 gcry_error_t ret = 0;
2106 // Convert each vector element to MPI_value
2107 for (i = 0; i < contained_elements; i++) {
2110 ret = gcry_mpi_scan (&session->a[i],
2112 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2113 PAILLIER_ELEMENT_LENGTH,
2116 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
2117 i, gcry_strsource (ret), gcry_strerror (ret));
2121 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2123 if (contained_elements == used_elements) {
2124 // single part finished
2125 session->state = SERVICE_REQUEST_RECEIVED;
2126 if (session->response) {
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, session->response)) {
2129 //something went wrong, remove it again...
2130 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2135 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2138 // multipart message
2143 for (i = 0; i < contained_elements; i++)
2145 gcry_mpi_release (session->a[i]);
2146 gcry_sexp_release (session->remote_pubkey);
2147 session->remote_pubkey = NULL;
2148 GNUNET_free (session->a);
2150 free_session (session);
2151 // and notify our client-session that we could not complete the session
2152 if (session->response)
2153 // we just found the responder session in this queue
2154 session->response->client_notification_task =
2155 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2157 return GNUNET_SYSERR;
2161 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2163 * @param cls closure (set from #GNUNET_MESH_connect)
2164 * @param tunnel connection to the other end
2165 * @param tunnel_ctx place to store local state associated with the tunnel
2166 * @param sender who sent the message
2167 * @param message the actual message
2168 * @param atsi performance data for the connection
2169 * @return #GNUNET_OK to keep the connection open,
2170 * #GNUNET_SYSERR to close it (signal serious error)
2173 handle_service_response_multipart (void *cls,
2174 struct GNUNET_MESH_Tunnel * tunnel,
2176 const struct GNUNET_MessageHeader * message)
2178 struct ServiceSession * session;
2179 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2180 unsigned char * current;
2183 uint32_t contained_element_count;
2187 GNUNET_assert (NULL != message);
2188 // are we in the correct state?
2189 session = (struct ServiceSession *) * tunnel_ctx;
2190 if (ALICE != session->role) {
2193 if (WAITING_FOR_MULTIPART_TRANSMISSION != session->state) {
2196 // shorter than minimum?
2197 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2200 contained_element_count = ntohl (msg->multipart_element_count);
2201 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2202 + 2 * contained_element_count * 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_element_count < contained_element_count)) {
2208 current = (unsigned char *) &msg[1];
2209 // Convert each k[][perm] to its MPI_value
2210 for (i = 0; i < contained_element_count; i++) {
2211 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2212 PAILLIER_ELEMENT_LENGTH, &read))) {
2213 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2214 GNUNET_break_op (0);
2217 current += PAILLIER_ELEMENT_LENGTH;
2218 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2219 PAILLIER_ELEMENT_LENGTH, &read))) {
2220 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2221 GNUNET_break_op (0);
2224 current += PAILLIER_ELEMENT_LENGTH;
2226 session->transferred_element_count += contained_element_count;
2227 if (session->transferred_element_count == session->used_element_count){
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!
2234 GNUNET_break_op (0);
2236 gcry_mpi_release (session->s);
2237 if (session->s_prime)
2238 gcry_mpi_release (session->s_prime);
2239 for (i = 0; session->r && i < session->transferred_element_count; i++)
2240 if (session->r[i]) gcry_mpi_release (session->r[i]);
2241 for (i = 0; session->r_prime && i < session->transferred_element_count; i++)
2242 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2243 GNUNET_free_non_null (session->r);
2244 GNUNET_free_non_null (session->r_prime);
2246 session->tunnel = NULL;
2247 // send message with product to client
2248 session->client_notification_task =
2249 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2251 // the tunnel has done its job, terminate our connection and the tunnel
2252 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2253 // just close the connection, as recommended by Christian
2254 return GNUNET_SYSERR;
2258 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2260 * @param cls closure (set from #GNUNET_MESH_connect)
2261 * @param tunnel connection to the other end
2262 * @param tunnel_ctx place to store local state associated with the tunnel
2263 * @param sender who sent the message
2264 * @param message the actual message
2265 * @param atsi performance data for the connection
2266 * @return #GNUNET_OK to keep the connection open,
2267 * #GNUNET_SYSERR to close it (we are done)
2270 handle_service_response (void *cls,
2271 struct GNUNET_MESH_Tunnel * tunnel,
2273 const struct GNUNET_MessageHeader * message)
2275 struct ServiceSession * session;
2276 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2277 unsigned char * current;
2280 uint32_t contained_element_count;
2284 GNUNET_assert (NULL != message);
2285 session = (struct ServiceSession *) * tunnel_ctx;
2286 if (ALICE != session->role) {
2287 GNUNET_break_op (0);
2288 return GNUNET_SYSERR;
2291 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2293 //we need at least a peer and one message id to compare
2294 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size)) {
2295 GNUNET_break_op (0);
2298 contained_element_count = ntohl (msg->contained_element_count);
2299 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2300 + 2 * contained_element_count * PAILLIER_ELEMENT_LENGTH
2301 + 2 * PAILLIER_ELEMENT_LENGTH;
2302 //sanity check: is the message as long as the message_count fields suggests?
2303 if ((ntohs (msg->header.size) != msg_size) || (session->used_element_count < contained_element_count)) {
2304 GNUNET_break_op (0);
2307 session->transferred_element_count = contained_element_count;
2309 current = (unsigned char *) &msg[1];
2310 if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2311 PAILLIER_ELEMENT_LENGTH, &read))) {
2312 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2313 GNUNET_break_op (0);
2316 current += PAILLIER_ELEMENT_LENGTH;
2318 if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2319 PAILLIER_ELEMENT_LENGTH, &read))) {
2320 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2321 GNUNET_break_op (0);
2324 current += PAILLIER_ELEMENT_LENGTH;
2325 session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2326 session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2327 // Convert each k[][perm] to its MPI_value
2328 for (i = 0; i < contained_element_count; i++) {
2329 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2330 PAILLIER_ELEMENT_LENGTH, &read))) {
2331 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2332 GNUNET_break_op (0);
2335 current += PAILLIER_ELEMENT_LENGTH;
2336 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2337 PAILLIER_ELEMENT_LENGTH, &read))) {
2338 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2339 GNUNET_break_op (0);
2342 current += PAILLIER_ELEMENT_LENGTH;
2344 if (session->transferred_element_count == session->used_element_count){
2345 session->state = SERVICE_RESPONSE_RECEIVED;
2346 session->product = compute_scalar_product (session);
2347 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2352 gcry_mpi_release (session->s);
2353 if (session->s_prime)
2354 gcry_mpi_release (session->s_prime);
2355 for (i = 0; session->r && i < contained_element_count; i++)
2356 if (session->r[i]) gcry_mpi_release (session->r[i]);
2357 for (i = 0; session->r_prime && i < contained_element_count; i++)
2358 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2359 GNUNET_free_non_null (session->r);
2360 GNUNET_free_non_null (session->r_prime);
2362 session->tunnel = NULL;
2363 // send message with product to client
2364 session->client_notification_task =
2365 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2367 // the tunnel has done its job, terminate our connection and the tunnel
2368 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2369 // just close the connection, as recommended by Christian
2370 return GNUNET_SYSERR;
2374 * Task run during shutdown.
2380 shutdown_task (void *cls,
2381 const struct GNUNET_SCHEDULER_TaskContext *tc)
2383 struct ServiceSession * session;
2384 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2386 do_shutdown = GNUNET_YES;
2388 // terminate all owned open tunnels.
2389 for (session = from_client_head; NULL != session; session = session->next) {
2390 if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2391 GNUNET_MESH_tunnel_destroy (session->tunnel);
2392 session->tunnel = NULL;
2394 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2395 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2396 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2398 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2399 GNUNET_SCHEDULER_cancel (session->service_request_task);
2400 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2402 if (NULL != session->client) {
2403 GNUNET_SERVER_client_disconnect (session->client);
2404 session->client = NULL;
2407 for (session = from_service_head; NULL != session; session = session->next)
2408 if (NULL != session->tunnel) {
2409 GNUNET_MESH_tunnel_destroy (session->tunnel);
2410 session->tunnel = NULL;
2414 GNUNET_MESH_disconnect (my_mesh);
2420 * Initialization of the program and message handlers
2422 * @param cls closure
2423 * @param server the initialized server
2424 * @param c configuration to use
2428 struct GNUNET_SERVER_Handle *server,
2429 const struct GNUNET_CONFIGURATION_Handle *c)
2431 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2432 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2433 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2436 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2437 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2438 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2439 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2440 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2443 static const uint32_t ports[] = {
2444 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2447 //generate private/public key set
2448 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2450 // register server callbacks and disconnect handler
2451 GNUNET_SERVER_add_handlers (server, server_handlers);
2452 GNUNET_SERVER_disconnect_notify (server,
2453 &handle_client_disconnect,
2455 GNUNET_break (GNUNET_OK ==
2456 GNUNET_CRYPTO_get_peer_identity (c,
2458 my_mesh = GNUNET_MESH_connect (c, NULL,
2459 &tunnel_incoming_handler,
2460 &tunnel_destruction_handler,
2461 mesh_handlers, ports);
2463 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2464 GNUNET_SCHEDULER_shutdown ();
2467 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2468 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2474 * The main function for the scalarproduct service.
2476 * @param argc number of arguments from the command line
2477 * @param argv command line arguments
2478 * @return 0 ok, 1 on error
2481 main (int argc, char *const *argv)
2483 return (GNUNET_OK ==
2484 GNUNET_SERVICE_run (argc, argv,
2486 GNUNET_SERVICE_OPTION_NONE,
2487 &run, NULL)) ? 0 : 1;
2490 /* end of gnunet-service-ext.c */