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 WAITING_FOR_BOBS_CONNECT,
48 MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED,
49 WAITING_FOR_RESPONSE_FROM_SERVICE,
50 REQUEST_FROM_SERVICE_RECEIVED,
55 * role a peer in a session can assume
65 * A scalarproduct session which tracks:
67 * a request form the client to our final response.
69 * a request from a service to us(service).
74 * the role this peer has
79 * session information is kept in a DLL
81 struct ServiceSession *next;
84 * session information is kept in a DLL
86 struct ServiceSession *prev;
89 * (hopefully) unique transaction ID
91 struct GNUNET_HashCode key;
94 * state of the session
96 enum SessionState state;
99 * Alice or Bob's peerID
101 struct GNUNET_PeerIdentity peer;
104 * the client this request is related to
106 struct GNUNET_SERVER_Client * client;
109 * how many elements we were supplied with from the client
111 uint16_t element_count;
114 * how many elements actually are used after applying the mask
116 uint16_t used_element_count;
119 * how many bytes the mask is long.
120 * just for convenience so we don't have to re-re-re calculate it each time
122 uint16_t mask_length;
125 * all the vector elements we received
130 * mask of which elements to check
132 unsigned char * mask;
135 * Public key of the remote service, only used by bob
137 gcry_sexp_t remote_pubkey;
140 * E(ai)(Bob) or ai(Alice) after applying the mask
145 * The computed scalar
150 * My transmit handle for the current message to a alice/bob
152 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
155 * My transmit handle for the current message to the client
157 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
160 * tunnel-handle associated with our mesh handle
162 struct GNUNET_MESH_Tunnel * tunnel;
167 * We need to do a minimum of bookkeeping to maintain track of our transmit handles.
168 * each msg is associated with a session and handle. using this information we can determine which msg was sent.
173 * The handle used to transmit with this request
175 void ** transmit_handle;
178 * The message to send
180 struct GNUNET_MessageHeader * msg;
183 ///////////////////////////////////////////////////////////////////////////////
185 ///////////////////////////////////////////////////////////////////////////////
189 * Handle to the core service (NULL until we've connected to it).
191 static struct GNUNET_MESH_Handle *my_mesh;
194 * The identity of this host.
196 static struct GNUNET_PeerIdentity me;
199 * Service's own public key represented as string
201 static unsigned char * my_pubkey_external;
204 * Service's own public key represented as string
206 static uint16_t my_pubkey_external_length = 0;
211 static gcry_mpi_t my_n;
214 * Service's own n^2 (kept for performance)
216 static gcry_mpi_t my_nsquare;
219 * Service's own public exponent
221 static gcry_mpi_t my_g;
224 * Service's own private multiplier
226 static gcry_mpi_t my_mu;
229 * Service's own private exponent
231 static gcry_mpi_t my_lambda;
234 * Service's offset for values that could possibly be negative but are plaintext for encryption.
236 static gcry_mpi_t my_offset;
239 * Head of our double linked list for client-requests sent to us.
240 * for all of these elements we calculate a scalar product with a remote peer
241 * split between service->service and client->service for simplicity
243 static struct ServiceSession * from_client_head;
245 * Tail of our double linked list for client-requests sent to us.
246 * for all of these elements we calculate a scalar product with a remote peer
247 * split between service->service and client->service for simplicity
249 static struct ServiceSession * from_client_tail;
252 * Head of our double linked list for service-requests sent to us.
253 * for all of these elements we help the requesting service in calculating a scalar product
254 * split between service->service and client->service for simplicity
256 static struct ServiceSession * from_service_head;
259 * Tail of our double linked list for service-requests sent to us.
260 * for all of these elements we help the requesting service in calculating a scalar product
261 * split between service->service and client->service for simplicity
263 static struct ServiceSession * from_service_tail;
266 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
268 static int do_shutdown;
270 ///////////////////////////////////////////////////////////////////////////////
272 ///////////////////////////////////////////////////////////////////////////////
275 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
280 gcry_sexp_t gen_parms;
282 gcry_sexp_t tmp_sexp;
291 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
292 GNUNET_assert (0 == gcry_sexp_build (&gen_parms, &erroff,
293 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
296 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_parms));
297 gcry_sexp_release (gen_parms);
299 // get n and d of our publickey as MPI
300 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
301 GNUNET_assert (tmp_sexp);
302 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
303 gcry_sexp_release (tmp_sexp);
304 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
305 GNUNET_assert (tmp_sexp);
306 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
307 gcry_sexp_release (tmp_sexp);
308 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
309 GNUNET_assert (tmp_sexp);
310 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
311 gcry_sexp_release (key);
313 tmp1 = gcry_mpi_new (0);
314 tmp2 = gcry_mpi_new (0);
315 gcd = gcry_mpi_new (0);
316 my_g = gcry_mpi_new (0);
317 my_mu = gcry_mpi_new (0);
318 my_nsquare = gcry_mpi_new (0);
319 my_lambda = gcry_mpi_new (0);
322 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
323 gcry_mpi_sub_ui (tmp1, p, 1);
324 gcry_mpi_sub_ui (tmp2, q, 1);
325 gcry_mpi_gcd (gcd, tmp1, tmp2);
326 gcry_mpi_set (my_lambda, tmp1);
327 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
328 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
331 gcry_mpi_mul (my_nsquare, my_n, my_n);
337 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
338 // g must be smaller than n^2
339 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
342 // g must have gcd == 1 with n^2
343 gcry_mpi_gcd (gcd, my_g, my_nsquare);
345 while (gcry_mpi_cmp_ui (gcd, 1));
347 // is this a valid g?
348 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
349 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
350 gcry_mpi_sub_ui (tmp1, tmp1, 1);
351 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
352 gcry_mpi_gcd (gcd, tmp1, my_n);
354 while (gcry_mpi_cmp_ui (gcd, 1));
356 // calculate our mu based on g and n.
357 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
358 gcry_mpi_invm (my_mu, tmp1, my_n);
360 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
361 "(public-key (paillier (n %M)(g %M)))",
364 // get the length of this sexpression
365 my_pubkey_external_length = gcry_sexp_sprint (key,
370 GNUNET_assert (my_pubkey_external_length > 0);
371 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
373 // convert the sexpression to canonical format
374 gcry_sexp_sprint (key,
377 my_pubkey_external_length);
379 gcry_sexp_release (key);
381 // offset has to be sufficiently small to allow computation of:
382 // m1+m2 mod n == (S + a) + (S + b) mod n,
383 // if we have more complex operations, this factor needs to be lowered
384 my_offset = gcry_mpi_new(KEYBITS/3);
385 gcry_mpi_set_bit(my_offset, KEYBITS/3);
387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
392 * If target != size, move target bytes to the
393 * end of the size-sized buffer and zero out the
394 * first target-size bytes.
396 * @param buf original buffer
397 * @param size number of bytes in the buffer
398 * @param target target size of the buffer
401 adjust (unsigned char *buf, size_t size, size_t target)
405 memmove (&buf[target - size], buf, size);
406 memset (buf, 0, target - size);
412 * encrypts an element using the paillier crypto system
414 * @param c ciphertext (output)
416 * @param g the public base
417 * @param n the module from which which r is chosen (Z*_n)
418 * @param n_square the module for encryption, for performance reasons.
421 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
425 GNUNET_assert (tmp = gcry_mpi_new (0));
427 while (0 >= gcry_mpi_cmp_ui (tmp, 1))
429 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
430 // r must be 1 < r < n
433 gcry_mpi_powm (c, g, m, n_square);
434 gcry_mpi_powm (tmp, tmp, n, n_square);
435 gcry_mpi_mulm (c, tmp, c, n_square);
437 gcry_mpi_release (tmp);
441 * decrypts an element using the paillier crypto system
443 * @param m plaintext (output)
444 * @param c the ciphertext
445 * @param mu the modifier to correct encryption
446 * @param lambda the private exponent
447 * @param n the outer module for decryption
448 * @param n_square the inner module for decryption
451 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)
453 gcry_mpi_powm (m, c, lambda, n_square);
454 gcry_mpi_sub_ui (m, m, 1);
455 gcry_mpi_div (m, NULL, m, n, 0);
456 gcry_mpi_mulm (m, m, mu, n);
461 * computes the square sum over a vector of a given length.
463 * @param vector the vector to encrypt
464 * @param length the length of the vector
465 * @return an MPI value containing the calculated sum, never NULL
468 compute_square_sum (gcry_mpi_t * vector, uint16_t length)
474 GNUNET_assert (sum = gcry_mpi_new (0));
475 GNUNET_assert (elem = gcry_mpi_new (0));
477 // calculare E(sum (ai ^ 2), publickey)
478 for (i = 0; i < length; i++)
480 gcry_mpi_mul (elem, vector[i], vector[i]);
481 gcry_mpi_add (sum, sum, elem);
483 gcry_mpi_release (elem);
490 * Primitive callback for copying over a message, as they
491 * usually are too complex to be handled in the callback itself.
492 * clears a session-callback, if a session was handed over and the transmit handle was stored
494 * @param cls the message object
495 * @param size the size of the buffer we got
496 * @param buf the buffer to copy the message to
497 * @return 0 if we couldn't copy, else the size copied over
500 do_send_message (void *cls, size_t size, void *buf)
502 struct MessageObject * info = cls;
503 struct GNUNET_MessageHeader * msg;
506 GNUNET_assert (info);
511 if (ntohs (msg->size) == size)
513 memcpy (buf, msg, size);
517 // reset the transmit handle, if necessary
518 if (info->transmit_handle)
519 *info->transmit_handle = NULL;
521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
522 "Sent a message of type %hu.\n",
531 * initializes a new vector with fresh MPI values (=0) of a given length
533 * @param length of the vector to create
534 * @return the initialized vector, never NULL
537 initialize_mpi_vector (uint16_t length)
540 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
542 for (i = 0; i < length; i++)
543 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
549 * permutes an MPI vector according to the given permutation vector
551 * @param vector the vector to permuted
552 * @param perm the permutation to use
553 * @param length the length of the vectors
554 * @return the permuted vector (same as input), never NULL
557 permute_vector (gcry_mpi_t * vector,
561 gcry_mpi_t tmp[length];
564 GNUNET_assert (length > 0);
567 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
569 // permute vector according to given
570 for (i = 0; i < length; i++)
571 vector[i] = tmp[perm[i]];
578 * Populate a vector with random integer values and convert them to
580 * @param length the length of the vector we must generate
581 * @return an array of MPI values with random values
584 generate_random_vector (uint16_t length)
586 gcry_mpi_t * random_vector;
590 random_vector = initialize_mpi_vector (length);
591 for (i = 0; i < length; i++)
593 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
595 // long to gcry_mpi_t
597 gcry_mpi_sub_ui (random_vector[i],
601 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
604 return random_vector;
609 * Finds a not terminated client/service session in the
610 * given DLL based on session key, element count and state.
612 * @param tail - the tail of the DLL
613 * @param my - the session to compare it to
614 * @return a pointer to a matching session,
617 static struct ServiceSession *
618 find_matching_session (struct ServiceSession * tail,
619 const struct GNUNET_HashCode * key,
620 uint16_t element_count,
621 enum SessionState * state,
622 const struct GNUNET_PeerIdentity * peerid)
624 struct ServiceSession * curr;
626 for (curr = tail; NULL != curr; curr = curr->prev)
628 // if the key matches, and the element_count is same
629 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
630 && (curr->element_count == element_count))
632 // if incoming state is NULL OR is same as state of the queued request
633 if ((NULL == state) || (curr->state == *state))
635 // if peerid is NULL OR same as the peer Id in the queued request
637 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
638 // matches and is not an already terminated session
649 destroy_tunnel (void *cls,
650 const struct GNUNET_SCHEDULER_TaskContext *tc)
652 struct ServiceSession * session = cls;
656 GNUNET_MESH_tunnel_destroy (session->tunnel);
657 session->tunnel = NULL;
659 session->service_transmit_handle = NULL;
660 // we need to set this to NULL so there is no problem with double-cancel later on.
665 free_session (struct ServiceSession * session)
669 if (FINALIZED != session->state)
673 for (i = 0; i < session->used_element_count; i++)
674 gcry_mpi_release (session->a[i]);
676 GNUNET_free (session->a);
678 if (session->product)
679 gcry_mpi_release (session->product);
681 if (session->remote_pubkey)
682 gcry_sexp_release (session->remote_pubkey);
684 GNUNET_free_non_null (session->vector);
687 GNUNET_free (session);
689 ///////////////////////////////////////////////////////////////////////////////
690 // Event and Message Handlers
691 ///////////////////////////////////////////////////////////////////////////////
695 * A client disconnected.
697 * Remove the associated session(s), release datastructures
698 * and cancel pending outgoing transmissions to the client.
699 * if the session has not yet completed, we also cancel Alice's request to Bob.
701 * @param cls closure, NULL
702 * @param client identification of the client
705 handle_client_disconnect (void *cls,
706 struct GNUNET_SERVER_Client
709 struct ServiceSession * elem;
710 struct ServiceSession * next;
712 // start from the tail, old stuff will be there...
713 for (elem = from_client_head; NULL != elem; elem = next)
716 if (elem->client != client)
719 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Client (%p) disconnected from us.\n"), client);
720 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, elem);
722 if (!(elem->role == BOB && elem->state == FINALIZED))
724 //we MUST terminate any client message underway
725 if (elem->service_transmit_handle && elem->tunnel)
726 GNUNET_MESH_notify_transmit_ready_cancel (elem->service_transmit_handle);
727 if (elem->tunnel && elem->state == WAITING_FOR_RESPONSE_FROM_SERVICE)
728 destroy_tunnel (elem, NULL);
736 * Notify the client that the session has succeeded or failed completely.
737 * This message gets sent to
738 * * alice's client if bob disconnected or to
739 * * bob's client if the operation completed or alice disconnected
741 * @param client_session the associated client session
742 * @return GNUNET_NO, if we could not notify the client
743 * GNUNET_YES if we notified it.
746 prepare_client_end_notification (void * cls,
747 const struct GNUNET_SCHEDULER_TaskContext * tc)
749 struct ServiceSession * session = cls;
750 struct GNUNET_SCALARPRODUCT_client_response * msg;
751 struct MessageObject * msg_obj;
753 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
754 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
755 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
756 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
757 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
758 // 0 size and the first char in the product is 0, which should never be zero if encoding is used.
759 msg->product_length = htonl (0);
761 msg_obj = GNUNET_new (struct MessageObject);
762 msg_obj->msg = &msg->header;
763 msg_obj->transmit_handle = NULL; // do not reset the transmit handle, please
765 //transmit this message to our client
766 session->client_transmit_handle =
767 GNUNET_SERVER_notify_transmit_ready (session->client,
768 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
769 GNUNET_TIME_UNIT_FOREVER_REL,
774 // if we could not even queue our request, something is wrong
775 if ( ! session->client_transmit_handle)
778 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)! This is OK if it was disconnected beforehand already.\n"), session->client);
779 // usually gets freed by do_send_message
780 GNUNET_free (msg_obj);
784 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
786 free_session(session);
792 * generates the response message to be sent to alice after computing
793 * the values (1), (2), S and S'
794 * (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)})$
795 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
796 * S: $S := E_A(sum (r_i + b_i)^2)$
797 * S': $S' := E_A(sum r_i^2)$
799 * @param r (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)})$
800 * @param r_prime (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
801 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
802 * @param s_prime S': $S' := E_A(sum r_i^2)$
803 * @param request the associated requesting session with alice
804 * @param response the associated responder session with bob's client
805 * @return GNUNET_SYSERR if the function was called with NULL parameters or if there was an error
806 * GNUNET_NO if we could not send our message
807 * GNUNET_OK if the operation succeeded
810 prepare_service_response (gcry_mpi_t * r,
811 gcry_mpi_t * r_prime,
814 struct ServiceSession * request,
815 struct ServiceSession * response)
817 struct GNUNET_SCALARPRODUCT_service_response * msg;
818 uint16_t msg_length = 0;
819 unsigned char * current = NULL;
820 unsigned char * element_exported = NULL;
821 size_t element_length = 0;
824 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
825 + 2 * request->used_element_count * PAILLIER_ELEMENT_LENGTH // kp, kq
826 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
828 msg = GNUNET_malloc (msg_length);
830 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
831 msg->header.size = htons (msg_length);
832 msg->element_count = htons (request->element_count);
833 msg->used_element_count = htons (request->used_element_count);
834 memcpy (&msg->key, &request->key, sizeof (struct GNUNET_HashCode));
835 current = (unsigned char *) &msg[1];
837 // 4 times the same logics with slight variations.
838 // doesn't really justify having 2 functions for that
839 // so i put it into blocks to enhance readability
842 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
843 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
844 element_exported, PAILLIER_ELEMENT_LENGTH,
847 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
848 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
849 GNUNET_free (element_exported);
850 current += PAILLIER_ELEMENT_LENGTH;
855 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
856 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
857 element_exported, PAILLIER_ELEMENT_LENGTH,
860 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
861 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
862 GNUNET_free (element_exported);
863 current += PAILLIER_ELEMENT_LENGTH;
867 for (i = 0; i < request->used_element_count; i++)
869 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
870 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
871 element_exported, PAILLIER_ELEMENT_LENGTH,
874 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
875 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
876 GNUNET_free (element_exported);
877 current += PAILLIER_ELEMENT_LENGTH;
882 for (i = 0; i < request->used_element_count; i++)
884 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
885 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
886 element_exported, PAILLIER_ELEMENT_LENGTH,
889 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
890 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
891 GNUNET_free (element_exported);
892 current += PAILLIER_ELEMENT_LENGTH;
895 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= msg_length)
897 struct MessageObject * msg_obj;
899 msg_obj = GNUNET_new (struct MessageObject);
900 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
901 msg_obj->transmit_handle = (void *) &request->service_transmit_handle; //and reset the transmit handle
902 request->service_transmit_handle =
903 GNUNET_MESH_notify_transmit_ready (request->tunnel,
905 GNUNET_TIME_UNIT_FOREVER_REL,
909 // we don't care if it could be send or not. either way, the session is over for us.
910 request->state = FINALIZED;
911 response->state = FINALIZED;
915 // TODO FEATURE: fallback to fragmentation, in case the message is too long
916 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!)\n"));
919 //disconnect our client
920 if ( ! request->service_transmit_handle)
922 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
923 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, response);
924 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
925 &prepare_client_end_notification,
936 * (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)})$
937 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
938 * S: $S := E_A(\sum (r_i + b_i)^2)$
939 * S': $S' := E_A(\sum r_i^2)$
941 * @param request the requesting session + bob's requesting peer
942 * @param response the responding session + bob's client handle
943 * @return GNUNET_SYSERR if the computation failed
944 * GNUNET_OK if everything went well.
947 compute_service_response (struct ServiceSession * request,
948 struct ServiceSession * response)
952 int ret = GNUNET_SYSERR;
956 gcry_mpi_t * rand = NULL;
957 gcry_mpi_t * r = NULL;
958 gcry_mpi_t * r_prime = NULL;
961 gcry_mpi_t * a_pi_prime;
963 gcry_mpi_t * rand_pi;
964 gcry_mpi_t * rand_pi_prime;
966 gcry_mpi_t s_prime = NULL;
967 gcry_mpi_t remote_n = NULL;
968 gcry_mpi_t remote_nsquare;
969 gcry_mpi_t remote_g = NULL;
973 count = request->used_element_count;
975 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
976 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
977 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
978 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
979 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
980 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
982 // convert responder session to from long to mpi
983 for (i = 0, j = 0; i < response->element_count && j < count; i++)
985 if (request->mask[i / 8] & (1 << (i % 8)))
987 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
988 // long to gcry_mpi_t
989 if (0 > response->vector[i])
991 b[j] = gcry_mpi_new (0);
992 gcry_mpi_sub_ui (b[j], b[j], value);
996 b[j] = gcry_mpi_set_ui (NULL, value);
1001 GNUNET_free (response->vector);
1002 response->vector = NULL;
1004 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1007 GNUNET_break_op (0);
1008 gcry_sexp_release (request->remote_pubkey);
1009 request->remote_pubkey = NULL;
1012 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1016 gcry_sexp_release (tmp_exp);
1019 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1020 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1021 gcry_sexp_release (tmp_exp);
1022 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1023 gcry_sexp_release (request->remote_pubkey);
1024 request->remote_pubkey = NULL;
1027 GNUNET_break_op (0);
1028 gcry_mpi_release (remote_n);
1031 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1035 gcry_mpi_release (remote_n);
1036 gcry_sexp_release (tmp_exp);
1039 gcry_sexp_release (tmp_exp);
1041 // generate r, p and q
1042 rand = generate_random_vector (count);
1043 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1044 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1045 //initialize the result vectors
1046 r = initialize_mpi_vector (count);
1047 r_prime = initialize_mpi_vector (count);
1049 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1050 // those values, thus we can work with the references
1051 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1052 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1053 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1054 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1055 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1057 // generate p and q permutations for a, b and r
1058 GNUNET_assert (permute_vector (a_pi, p, count));
1059 GNUNET_assert (permute_vector (b_pi, p, count));
1060 GNUNET_assert (permute_vector (rand_pi, p, count));
1061 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1062 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1064 // encrypt the element
1065 // for the sake of readability I decided to have dedicated permutation
1066 // vectors, which get rid of all the lookups in p/q.
1067 // however, ap/aq are not absolutely necessary but are just abstraction
1068 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1069 for (i = 0; i < count; i++)
1071 // E(S - r_pi - b_pi)
1072 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1073 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1074 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1076 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1077 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1081 GNUNET_free (rand_pi);
1083 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1084 for (i = 0; i < count; i++)
1087 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1088 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1090 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1091 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1093 GNUNET_free (a_pi_prime);
1094 GNUNET_free (rand_pi_prime);
1096 // Calculate S' = E(SUM( r_i^2 ))
1097 s_prime = compute_square_sum (rand, count);
1098 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1100 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1101 for (i = 0; i < count; i++)
1103 gcry_mpi_add (rand[i], rand[i], b[i]);
1105 s = compute_square_sum (rand, count);
1106 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1107 gcry_mpi_release (remote_n);
1108 gcry_mpi_release (remote_g);
1109 gcry_mpi_release (remote_nsquare);
1111 // release r and tmp
1112 for (i = 0; i < count; i++)
1113 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1114 gcry_mpi_release (rand[i]);
1116 // copy the Kp[], Kq[], S and Stick into a new message
1117 if (GNUNET_YES != prepare_service_response (r, r_prime, s, s_prime, request, response))
1118 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1119 GNUNET_i2s (&request->peer));
1123 for (i = 0; i < count; i++)
1125 gcry_mpi_release (r_prime[i]);
1126 gcry_mpi_release (r[i]);
1129 gcry_mpi_release (s);
1130 gcry_mpi_release (s_prime);
1133 for (i = 0; i < count; i++)
1135 gcry_mpi_release (b[i]);
1136 gcry_mpi_release (request->a[i]);
1140 GNUNET_free (request->a);
1148 * Executed by Alice, fills in a service-request message and sends it to the given peer
1150 * @param session the session associated with this request, then also holds the CORE-handle
1151 * @return #GNUNET_SYSERR if we could not send the message
1152 * #GNUNET_NO if the message was too large
1153 * #GNUNET_OK if we sent it
1156 prepare_service_request (void *cls,
1157 const struct GNUNET_SCHEDULER_TaskContext *tc)
1159 struct ServiceSession * session = cls;
1160 unsigned char * current;
1161 struct GNUNET_SCALARPRODUCT_service_request * msg;
1162 struct MessageObject * msg_obj;
1165 uint16_t msg_length;
1166 size_t element_length = 0; //gets initialized by gcry_mpi_print, but the compiler doesn't know that
1170 GNUNET_assert (NULL != cls);
1171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1173 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1174 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1175 + session->mask_length
1176 + my_pubkey_external_length;
1178 if (GNUNET_SERVER_MAX_MESSAGE_SIZE < sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1179 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1180 + session->mask_length
1181 + my_pubkey_external_length)
1183 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1184 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1185 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1186 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1187 &prepare_client_end_notification,
1191 msg = GNUNET_malloc (msg_length);
1193 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1194 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1195 msg->mask_length = htons (session->mask_length);
1196 msg->pk_length = htons (my_pubkey_external_length);
1197 msg->used_element_count = htons (session->used_element_count);
1198 msg->element_count = htons (session->element_count);
1199 msg->header.size = htons (msg_length);
1201 // fill in the payload
1202 current = (unsigned char *) &msg[1];
1203 // copy over the mask
1204 memcpy (current, session->mask, session->mask_length);
1205 // copy over our public key
1206 current += session->mask_length;
1207 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1208 current += my_pubkey_external_length;
1210 // now copy over the element vector
1211 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1212 a = gcry_mpi_new (KEYBITS * 2);
1213 // encrypt our vector and generate string representations
1214 for (i = 0, j = 0; i < session->element_count; i++)
1216 // if this is a used element...
1217 if (session->mask[i / 8] & 1 << (i % 8))
1219 unsigned char * element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1220 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1222 a = gcry_mpi_set_ui (a, 0);
1223 // long to gcry_mpi_t
1224 if (session->vector[i] < 0)
1225 gcry_mpi_sub_ui (a, a, value);
1227 gcry_mpi_add_ui (a, a, value);
1229 session->a[j++] = gcry_mpi_set (NULL, a);
1230 gcry_mpi_add (a, a, my_offset);
1231 encrypt_element (a, a, my_g, my_n, my_nsquare);
1233 // get representation as string
1234 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1235 GNUNET_assert ( ! gcry_mpi_print (GCRYMPI_FMT_USG,
1236 element_exported, PAILLIER_ELEMENT_LENGTH,
1240 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1241 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1243 // copy over to the message
1244 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1245 current += PAILLIER_ELEMENT_LENGTH;
1248 gcry_mpi_release (a);
1250 msg_obj = GNUNET_new (struct MessageObject);
1251 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1252 msg_obj->transmit_handle = (void *) &session->service_transmit_handle; //and reset the transmit handle
1253 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting service request.\n"));
1255 //transmit via mesh messaging
1256 session->state = WAITING_FOR_RESPONSE_FROM_SERVICE;
1257 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1258 GNUNET_TIME_UNIT_FOREVER_REL,
1262 if ( ! session->service_transmit_handle)
1264 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not send mutlicast message to tunnel!\n"));
1265 GNUNET_free (msg_obj);
1267 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1268 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1269 &prepare_client_end_notification,
1275 * Handler for a client request message.
1276 * Can either be type A or B
1277 * A: request-initiation to compute a scalar product with a peer
1278 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1280 * @param cls closure
1281 * @param client identification of the client
1282 * @param message the actual message
1285 handle_client_request (void *cls,
1286 struct GNUNET_SERVER_Client *client,
1287 const struct GNUNET_MessageHeader *message)
1289 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1290 struct ServiceSession * session;
1291 uint16_t element_count;
1292 uint16_t mask_length;
1297 GNUNET_assert (message);
1299 //we need at least a peer and one message id to compare
1300 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size))
1302 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1303 _ ("Too short message received from client!\n"));
1304 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1308 msg_type = ntohs (msg->header.type);
1309 element_count = ntohs (msg->element_count);
1310 mask_length = ntohs (msg->mask_length);
1312 //sanity check: is the message as long as the message_count fields suggests?
1313 if (( ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_length))
1314 || (0 == element_count))
1316 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1317 _ ("Invalid message received from client, session information incorrect!\n"));
1318 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1322 // do we have a duplicate session here already?
1323 if (NULL != find_matching_session (from_client_tail,
1328 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Duplicate session information received, cannot create new session with key `%s'\n"), GNUNET_h2s (&msg->key));
1329 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1333 session = GNUNET_new (struct ServiceSession);
1334 session->client = client;
1335 session->element_count = element_count;
1336 session->mask_length = mask_length;
1337 // get our transaction key
1338 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1339 //allocate memory for vector and encrypted vector
1340 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1341 vector = (int32_t *) & msg[1];
1343 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type)
1345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), GNUNET_h2s (&session->key));
1347 session->role = ALICE;
1349 session->mask = GNUNET_malloc (mask_length);
1350 memcpy (session->mask, &vector[element_count], mask_length);
1352 // copy over the elements
1353 session->used_element_count = 0;
1354 for (i = 0; i < element_count; i++)
1356 session->vector[i] = ntohl (vector[i]);
1357 if (session->vector[i] == 0)
1358 session->mask[i / 8] &= ~(1 << (i % 8));
1359 if (session->mask[i / 8] & (1 << (i % 8)))
1360 session->used_element_count++;
1363 if ( ! session->used_element_count)
1365 GNUNET_break_op (0);
1366 GNUNET_free (session->vector);
1367 GNUNET_free (session->a);
1368 GNUNET_free (session);
1369 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1372 //session with ourself makes no sense!
1373 if ( ! memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1376 GNUNET_free (session->vector);
1377 GNUNET_free (session->a);
1378 GNUNET_free (session);
1379 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1383 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1384 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Creating new tunnel to for session with key %s.\n"), GNUNET_h2s (&session->key));
1385 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1386 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1388 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1391 //prepare_service_request, tunnel_peer_disconnect_handler,
1392 if ( ! session->tunnel)
1395 GNUNET_free (session->vector);
1396 GNUNET_free (session->a);
1397 GNUNET_free (session);
1398 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1401 session->state = WAITING_FOR_BOBS_CONNECT;
1402 GNUNET_SCHEDULER_add_now(&prepare_service_request, (void*) session);
1403 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1407 struct ServiceSession * requesting_session;
1408 enum SessionState needed_state = REQUEST_FROM_SERVICE_RECEIVED;
1410 session->role = BOB;
1411 session->mask = NULL;
1412 // copy over the elements
1413 session->used_element_count = element_count;
1414 for (i = 0; i < element_count; i++)
1415 session->vector[i] = ntohl (vector[i]);
1416 session->state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1418 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1419 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1420 //check if service queue contains a matching request
1421 requesting_session = find_matching_session (from_service_tail,
1423 session->element_count,
1424 &needed_state, NULL);
1425 if (NULL != requesting_session)
1427 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));
1428 if (GNUNET_OK != compute_service_response (requesting_session, session))
1430 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1431 GNUNET_SCHEDULER_add_now(&prepare_client_end_notification, session);
1435 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));
1436 // no matching session exists yet, store the response
1437 // for later processing by handle_service_request()
1443 * Function called for inbound tunnels.
1445 * @param cls closure
1446 * @param tunnel new handle to the tunnel
1447 * @param initiator peer that started the tunnel
1448 * @param atsi performance information for the tunnel
1449 * @return initial tunnel context for the tunnel
1450 * (can be NULL -- that's not an error)
1453 tunnel_incoming_handler (void *cls,
1454 struct GNUNET_MESH_Tunnel *tunnel,
1455 const struct GNUNET_PeerIdentity *initiator,
1459 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1461 memcpy (&c->peer, initiator, sizeof (struct GNUNET_PeerIdentity));
1468 * Function called whenever a tunnel is destroyed. Should clean up
1469 * any associated state.
1471 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1473 * @param cls closure (set from GNUNET_MESH_connect)
1474 * @param tunnel connection to the other end (henceforth invalid)
1475 * @param tunnel_ctx place where local state associated
1476 * with the tunnel is stored
1479 tunnel_destruction_handler (void *cls,
1480 const struct GNUNET_MESH_Tunnel *tunnel,
1483 struct ServiceSession * session = tunnel_ctx;
1484 struct ServiceSession * client_session;
1485 struct ServiceSession * curr;
1487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Peer disconnected, terminating session %s with peer (%s)\n"), GNUNET_h2s (&session->key), GNUNET_i2s (&session->peer));
1488 if (ALICE == session->role) {
1489 // as we have only one peer connected in each session, just remove the session
1491 if ((FINALIZED != session->state) && (!do_shutdown))
1493 for (curr = from_client_head; NULL != curr; curr = curr->next)
1494 if (curr == session)
1496 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1499 // FIXME: dangling tasks, code duplication, use-after-free, fun...
1500 GNUNET_SCHEDULER_add_now (&destroy_tunnel,
1502 // if this happened before we received the answer, we must terminate the session
1503 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1507 else { //(BOB == session->role)
1509 // remove the session, unless it has already been dequeued, but somehow still active
1510 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1511 for (curr = from_service_head; NULL != curr; curr = curr->next)
1512 if (curr == session)
1514 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1517 // there is a client waiting for this service session, terminate it, too!
1518 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1519 client_session = find_matching_session (from_client_tail,
1521 session->element_count,
1523 free_session (session);
1525 // the client has to check if it was waiting for a result
1526 // or if it was a responder, no point in adding more statefulness
1527 if (client_session && (!do_shutdown))
1529 // remove the session, we just found it in the queue, so it must be there
1530 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, client_session);
1531 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1539 * Compute our scalar product, done by Alice
1541 * @param session - the session associated with this computation
1542 * @param kp - (1) from the protocol definition:
1543 * $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)})$
1544 * @param kq - (2) from the protocol definition:
1545 * $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1546 * @param s - S from the protocol definition:
1547 * $S := E_A(\sum (r_i + b_i)^2)$
1548 * @param stick - S' from the protocol definition:
1549 * $S' := E_A(\sum r_i^2)$
1550 * @return product as MPI, never NULL
1553 compute_scalar_product (struct ServiceSession * session,
1554 gcry_mpi_t * r, gcry_mpi_t * r_prime, gcry_mpi_t s, gcry_mpi_t s_prime)
1565 count = session->used_element_count;
1566 tmp = gcry_mpi_new (KEYBITS);
1567 // due to the introduced static offset S, we now also have to remove this
1568 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1569 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1570 for (i = 0; i < count; i++)
1572 decrypt_element (r[i], r[i], my_mu, my_lambda, my_n, my_nsquare);
1573 gcry_mpi_sub(r[i],r[i],my_offset);
1574 gcry_mpi_sub(r[i],r[i],my_offset);
1575 decrypt_element (r_prime[i], r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1576 gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
1577 gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
1580 // calculate t = sum(ai)
1581 t = compute_square_sum (session->a, count);
1584 u = gcry_mpi_new (0);
1585 tmp = compute_square_sum (r, count);
1586 gcry_mpi_sub (u, u, tmp);
1587 gcry_mpi_release (tmp);
1590 utick = gcry_mpi_new (0);
1591 tmp = compute_square_sum (r_prime, count);
1592 gcry_mpi_sub (utick, utick, tmp);
1594 GNUNET_assert (p = gcry_mpi_new (0));
1595 GNUNET_assert (ptick = gcry_mpi_new (0));
1598 decrypt_element (s, s, my_mu, my_lambda, my_n, my_nsquare);
1599 decrypt_element (s_prime, s_prime, my_mu, my_lambda, my_n, my_nsquare);
1602 gcry_mpi_add (p, s, t);
1603 gcry_mpi_add (p, p, u);
1606 gcry_mpi_add (ptick, s_prime, t);
1607 gcry_mpi_add (ptick, ptick, utick);
1609 gcry_mpi_release (t);
1610 gcry_mpi_release (u);
1611 gcry_mpi_release (utick);
1614 gcry_mpi_sub (p, p, ptick);
1615 gcry_mpi_release (ptick);
1616 tmp = gcry_mpi_set_ui (tmp, 2);
1617 gcry_mpi_div (p, NULL, p, tmp, 0);
1619 gcry_mpi_release (tmp);
1620 for (i = 0; i < count; i++)
1621 gcry_mpi_release (session->a[i]);
1622 GNUNET_free (session->a);
1630 * prepare the response we will send to alice or bobs' clients.
1631 * in Bobs case the product will be NULL.
1633 * @param session the session associated with our client.
1636 prepare_client_response (void *cls,
1637 const struct GNUNET_SCHEDULER_TaskContext *tc)
1639 struct ServiceSession * session = cls;
1640 struct GNUNET_SCALARPRODUCT_client_response * msg;
1641 unsigned char * product_exported = NULL;
1642 size_t product_length = 0;
1643 uint16_t msg_length = 0;
1644 struct MessageObject * msg_obj;
1648 if (session->product)
1650 gcry_mpi_t value = gcry_mpi_new(0);
1652 sign = gcry_mpi_cmp_ui(session->product, 0);
1653 // libgcrypt can not handle a print of a negative number
1656 gcry_mpi_sub(value, value, session->product);
1660 gcry_mpi_add(value, value, session->product);
1663 // get representation as string
1664 // unfortunately libgcrypt is too stupid to implement print-support in
1665 // signed GCRYMPI_FMT_STD format, and simply asserts in that case.
1666 // here is the associated sourcecode:
1667 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1669 GNUNET_assert ( ! gcry_mpi_aprint (GCRYMPI_FMT_USG, // FIXME: just log (& survive!)
1674 gcry_mpi_release (session->product);
1675 session->product = NULL;
1678 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) + product_length;
1679 msg = GNUNET_malloc (msg_length);
1680 memcpy (&msg[1], product_exported, product_length);
1681 GNUNET_free_non_null (product_exported);
1682 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1683 msg->header.size = htons (msg_length);
1685 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1686 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1687 msg->product_length = htonl (product_length);
1689 msg_obj = GNUNET_new (struct MessageObject);
1690 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1691 msg_obj->transmit_handle = NULL; // don't reset the transmit handle
1693 //transmit this message to our client
1694 session->client_transmit_handle = // FIXME: use after free possibility during shutdown
1695 GNUNET_SERVER_notify_transmit_ready (session->client,
1697 GNUNET_TIME_UNIT_FOREVER_REL,
1700 if ( ! session->client_transmit_handle)
1702 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)! This probably is OK if the client disconnected before us.\n"), session->client);
1703 session->client = NULL;
1704 // callback was not called!
1705 GNUNET_free (msg_obj);
1709 // gracefully sent message, just terminate session structure
1710 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sent result to client (%p), this session (%s) has ended!\n"), session->client, GNUNET_h2s (&session->key));
1711 free_session (session);
1716 * Handle a request from another service to calculate a scalarproduct with us.
1718 * @param cls closure (set from #GNUNET_MESH_connect)
1719 * @param tunnel connection to the other end
1720 * @param tunnel_ctx place to store local state associated with the tunnel
1721 * @param sender who sent the message
1722 * @param message the actual message
1723 * @param atsi performance data for the connection
1724 * @return #GNUNET_OK to keep the connection open,
1725 * #GNUNET_SYSERR to close it (signal serious error)
1728 handle_service_request (void *cls,
1729 struct GNUNET_MESH_Tunnel * tunnel,
1731 const struct GNUNET_MessageHeader * message)
1733 struct ServiceSession * session;
1734 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
1735 uint16_t mask_length;
1737 uint16_t used_elements;
1738 uint16_t element_count;
1739 uint16_t msg_length;
1740 unsigned char * current;
1741 struct ServiceSession * responder_session;
1743 enum SessionState needed_state;
1745 session = (struct ServiceSession *) * tunnel_ctx;
1746 if (BOB != session->role){
1748 return GNUNET_SYSERR;
1750 // is this tunnel already in use?
1751 if ( (session->next) || (from_service_head == session))
1754 return GNUNET_SYSERR;
1756 // Check if message was sent by me, which would be bad!
1757 if ( ! memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1760 GNUNET_free (session);
1761 return GNUNET_SYSERR;
1764 //we need at least a peer and one message id to compare
1765 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request))
1767 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
1768 GNUNET_free (session);
1769 return GNUNET_SYSERR;
1771 mask_length = ntohs (msg->mask_length);
1772 pk_length = ntohs (msg->pk_length);
1773 used_elements = ntohs (msg->used_element_count);
1774 element_count = ntohs (msg->element_count);
1775 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1776 + mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
1778 //sanity check: is the message as long as the message_count fields suggests?
1779 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements)
1780 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
1783 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer, message count does not match message length!\n"));
1784 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Used elements: %hu\nElement Count: %hu\nExpected Mask Length: %hu\nCalculated Masklength: %d\n"), used_elements, element_count, mask_length, (element_count / 8 + (element_count % 8 ? 1 : 0)));
1785 GNUNET_free (session);
1786 return GNUNET_SYSERR;
1788 if (find_matching_session (from_service_tail,
1794 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
1795 GNUNET_free (session);
1796 return GNUNET_SYSERR;
1799 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
1800 session->state = REQUEST_FROM_SERVICE_RECEIVED;
1801 session->element_count = ntohs (msg->element_count);
1802 session->used_element_count = used_elements;
1803 session->tunnel = tunnel;
1806 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1807 current = (unsigned char *) &msg[1];
1808 //preserve the mask, we will need that later on
1809 session->mask = GNUNET_malloc (mask_length);
1810 memcpy (session->mask, current, mask_length);
1812 current += mask_length;
1814 //convert the publickey to sexp
1815 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))
1817 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
1818 GNUNET_free (session->mask);
1819 GNUNET_free (session);
1820 return GNUNET_SYSERR;
1823 current += pk_length;
1825 //check if service queue contains a matching request
1826 needed_state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1827 responder_session = find_matching_session (from_client_tail,
1829 session->element_count,
1830 &needed_state, NULL);
1832 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1834 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1837 + used_elements * PAILLIER_ELEMENT_LENGTH)
1839 gcry_error_t ret = 0;
1840 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1841 // Convert each vector element to MPI_value
1842 for (i = 0; i < used_elements; i++)
1846 ret = gcry_mpi_scan (&session->a[i],
1848 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1849 PAILLIER_ELEMENT_LENGTH,
1853 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1854 i, gcry_strsource (ret), gcry_strerror (ret));
1858 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
1859 if (responder_session)
1861 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1862 if (GNUNET_OK != compute_service_response (session, responder_session))
1864 //something went wrong, remove it again...
1865 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1870 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1875 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1876 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1880 for (i = 0; i < used_elements; i++)
1882 gcry_mpi_release (session->a[i]);
1883 gcry_sexp_release (session->remote_pubkey);
1884 session->remote_pubkey = NULL;
1885 GNUNET_free_non_null (session->a);
1887 free_session (session);
1888 // and notify our client-session that we could not complete the session
1889 if (responder_session)
1891 // we just found the responder session in this queue
1892 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, responder_session);
1893 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1894 &prepare_client_end_notification,
1897 return GNUNET_SYSERR;
1902 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
1904 * @param cls closure (set from #GNUNET_MESH_connect)
1905 * @param tunnel connection to the other end
1906 * @param tunnel_ctx place to store local state associated with the tunnel
1907 * @param sender who sent the message
1908 * @param message the actual message
1909 * @param atsi performance data for the connection
1910 * @return #GNUNET_OK to keep the connection open,
1911 * #GNUNET_SYSERR to close it (signal serious error)
1914 handle_service_response (void *cls,
1915 struct GNUNET_MESH_Tunnel * tunnel,
1917 const struct GNUNET_MessageHeader * message)
1920 struct ServiceSession * session;
1921 struct GNUNET_SCALARPRODUCT_service_response * msg = (struct GNUNET_SCALARPRODUCT_service_response *) message;
1922 unsigned char * current;
1924 gcry_mpi_t s = NULL;
1925 gcry_mpi_t s_prime = NULL;
1928 uint16_t used_element_count;
1930 gcry_mpi_t * r = NULL;
1931 gcry_mpi_t * r_prime = NULL;
1934 GNUNET_assert (NULL != message);
1935 session = (struct ServiceSession *) * tunnel_ctx;
1936 if (ALICE != session->role){
1938 return GNUNET_SYSERR;
1941 count = session->used_element_count;
1942 session->product = NULL;
1944 //we need at least a peer and one message id to compare
1945 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size))
1947 GNUNET_break_op (0);
1950 used_element_count = ntohs (msg->used_element_count);
1951 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
1952 + 2 * used_element_count * PAILLIER_ELEMENT_LENGTH
1953 + 2 * PAILLIER_ELEMENT_LENGTH;
1954 //sanity check: is the message as long as the message_count fields suggests?
1955 if ((ntohs (msg->header.size) != msg_size) || (count != used_element_count))
1957 GNUNET_break_op (0);
1962 current = (unsigned char *) &msg[1];
1963 if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current,
1964 PAILLIER_ELEMENT_LENGTH, &read)))
1966 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1967 GNUNET_break_op (0);
1970 current += PAILLIER_ELEMENT_LENGTH;
1972 if (0 != (rc = gcry_mpi_scan (&s_prime, GCRYMPI_FMT_USG, current,
1973 PAILLIER_ELEMENT_LENGTH, &read)))
1975 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1976 GNUNET_break_op (0);
1979 current += PAILLIER_ELEMENT_LENGTH;
1981 r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1982 // Convert each kp[] to its MPI_value
1983 for (i = 0; i < count; i++)
1985 if (0 != (rc = gcry_mpi_scan (&r[i], GCRYMPI_FMT_USG, current,
1986 PAILLIER_ELEMENT_LENGTH, &read)))
1988 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1989 GNUNET_break_op (0);
1992 current += PAILLIER_ELEMENT_LENGTH;
1996 r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1997 // Convert each kq[] to its MPI_value
1998 for (i = 0; i < count; i++)
2000 if (0 != (rc = gcry_mpi_scan (&r_prime[i], GCRYMPI_FMT_USG, current,
2001 PAILLIER_ELEMENT_LENGTH, &read)))
2003 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2004 GNUNET_break_op (0);
2007 current += PAILLIER_ELEMENT_LENGTH;
2010 session->product = compute_scalar_product (session, r, r_prime, s, s_prime);
2014 gcry_mpi_release (s);
2016 gcry_mpi_release (s_prime);
2017 for (i = 0; r && i < count; i++)
2018 if (r[i]) gcry_mpi_release (r[i]);
2019 for (i = 0; r_prime && i < count; i++)
2020 if (r_prime[i]) gcry_mpi_release (r_prime[i]);
2021 GNUNET_free_non_null (r);
2022 GNUNET_free_non_null (r_prime);
2024 session->state = FINALIZED;
2025 // the tunnel has done its job, terminate our connection and the tunnel
2026 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2027 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
2028 GNUNET_SCHEDULER_add_now (&destroy_tunnel, session); // FIXME: use after free!
2029 // send message with product to client
2030 /* session->current_task = */ GNUNET_SCHEDULER_add_now (&prepare_client_response, session); // FIXME: dangling task!
2032 // if success: terminate the session gracefully, else terminate with error
2037 * Task run during shutdown.
2043 shutdown_task (void *cls,
2044 const struct GNUNET_SCHEDULER_TaskContext *tc)
2046 struct ServiceSession * curr;
2047 struct ServiceSession * next;
2048 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2050 do_shutdown = GNUNET_YES;
2051 // terminate all owned open tunnels.
2052 for (curr = from_client_head; NULL != curr; curr = next)
2055 if (FINALIZED != curr->state)
2057 destroy_tunnel (curr, NULL);
2058 curr->state = FINALIZED;
2063 GNUNET_MESH_disconnect (my_mesh);
2070 * Initialization of the program and message handlers
2072 * @param cls closure
2073 * @param server the initialized server
2074 * @param c configuration to use
2078 struct GNUNET_SERVER_Handle *server,
2079 const struct GNUNET_CONFIGURATION_Handle *c)
2081 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2082 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2083 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2086 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2087 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2088 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2091 static const uint32_t ports[] = {
2092 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2095 //generate private/public key set
2096 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2098 // register server callbacks and disconnect handler
2099 GNUNET_SERVER_add_handlers (server, server_handlers);
2100 GNUNET_SERVER_disconnect_notify (server,
2101 &handle_client_disconnect,
2103 GNUNET_break (GNUNET_OK ==
2104 GNUNET_CRYPTO_get_host_identity (c,
2106 my_mesh = GNUNET_MESH_connect (c, NULL,
2107 &tunnel_incoming_handler,
2108 &tunnel_destruction_handler,
2109 mesh_handlers, ports);
2112 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2113 GNUNET_SCHEDULER_shutdown ();
2116 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2117 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2124 * The main function for the scalarproduct service.
2126 * @param argc number of arguments from the command line
2127 * @param argv command line arguments
2128 * @return 0 ok, 1 on error
2131 main (int argc, char *const *argv)
2133 return (GNUNET_OK ==
2134 GNUNET_SERVICE_run (argc, argv,
2136 GNUNET_SERVICE_OPTION_NONE,
2137 &run, NULL)) ? 0 : 1;
2140 /* end of gnunet-service-ext.c */