2 This file is part of GNUnet.
3 (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file scalarproduct/gnunet-service-scalarproduct.c
23 * @brief scalarproduct service implementation
24 * @author Christian M. Fuchs
28 #include "gnunet_util_lib.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_mesh_service.h"
31 #include "gnunet_applications.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_scalarproduct_service.h"
34 #include "scalarproduct.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
38 ///////////////////////////////////////////////////////////////////////////////
39 // Service Structure Definitions
40 ///////////////////////////////////////////////////////////////////////////////
43 * state a session can be in
47 CLIENT_REQUEST_RECEIVED,
48 WAITING_FOR_BOBS_CONNECT,
49 CLIENT_RESPONSE_RECEIVED,
50 WAITING_FOR_SERVICE_REQUEST,
51 WAITING_FOR_MULTIPART_TRANSMISSION,
52 WAITING_FOR_SERVICE_RESPONSE,
53 SERVICE_REQUEST_RECEIVED,
54 SERVICE_RESPONSE_RECEIVED,
59 * role a peer in a session can assume
68 * A scalarproduct session which tracks:
70 * a request form the client to our final response.
72 * a request from a service to us(service).
77 * the role this peer has
82 * session information is kept in a DLL
84 struct ServiceSession *next;
87 * session information is kept in a DLL
89 struct ServiceSession *prev;
92 * (hopefully) unique transaction ID
94 struct GNUNET_HashCode key;
97 * state of the session
99 enum SessionState state;
102 * Alice or Bob's peerID
104 struct GNUNET_PeerIdentity peer;
107 * the client this request is related to
109 struct GNUNET_SERVER_Client * client;
112 * The message to send
114 struct GNUNET_MessageHeader * msg;
117 * how many elements we were supplied with from the client
122 * how many elements actually are used after applying the mask
127 * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
129 uint32_t transferred;
132 * index of the last transferred element for multipart messages
134 uint32_t last_processed;
137 * how many bytes the mask is long.
138 * just for convenience so we don't have to re-re-re calculate it each time
140 uint32_t mask_length;
143 * all the vector elements we received
148 * mask of which elements to check
150 unsigned char * mask;
153 * Public key of the remote service, only used by bob
155 gcry_sexp_t remote_pubkey;
158 * E(ai)(Bob) or ai(Alice) after applying the mask
163 * Bob's permutation p of R
168 * Bob's permutation q of R
170 gcry_mpi_t * r_prime;
183 * Bobs matching response session from the client
185 struct ServiceSession * response;
188 * The computed scalar
193 * My transmit handle for the current message to a alice/bob
195 struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
198 * My transmit handle for the current message to the client
200 struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
203 * tunnel-handle associated with our mesh handle
205 struct GNUNET_MESH_Tunnel * tunnel;
208 * Handle to a task that sends a msg to the our client
210 GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
213 * Handle to a task that sends a msg to the our peer
215 GNUNET_SCHEDULER_TaskIdentifier service_request_task;
218 ///////////////////////////////////////////////////////////////////////////////
219 // Forward Delcarations
220 ///////////////////////////////////////////////////////////////////////////////
223 * Send a multi part chunk of a service request from alice to bob.
224 * This element only contains a part of the elements-vector (session->a[]),
225 * mask and public key set have to be contained within the first message
227 * This allows a ~32kbit key length while using 32000 elements or 62000 elements per request.
229 * @param cls the associated service session
232 prepare_service_request_multipart (void *cls);
235 * Send a multi part chunk of a service response from bob to alice.
236 * This element only contains the two permutations of R, R'.
238 * @param cls the associated service session
241 prepare_service_response_multipart (void *cls);
244 ///////////////////////////////////////////////////////////////////////////////
246 ///////////////////////////////////////////////////////////////////////////////
250 * Handle to the core service (NULL until we've connected to it).
252 static struct GNUNET_MESH_Handle *my_mesh;
255 * The identity of this host.
257 static struct GNUNET_PeerIdentity me;
260 * Service's own public key represented as string
262 static unsigned char * my_pubkey_external;
265 * Service's own public key represented as string
267 static uint32_t my_pubkey_external_length = 0;
272 static gcry_mpi_t my_n;
275 * Service's own n^2 (kept for performance)
277 static gcry_mpi_t my_nsquare;
280 * Service's own public exponent
282 static gcry_mpi_t my_g;
285 * Service's own private multiplier
287 static gcry_mpi_t my_mu;
290 * Service's own private exponent
292 static gcry_mpi_t my_lambda;
295 * Service's offset for values that could possibly be negative but are plaintext for encryption.
297 static gcry_mpi_t my_offset;
300 * Head of our double linked list for client-requests sent to us.
301 * for all of these elements we calculate a scalar product with a remote peer
302 * split between service->service and client->service for simplicity
304 static struct ServiceSession * from_client_head;
306 * Tail of our double linked list for client-requests sent to us.
307 * for all of these elements we calculate a scalar product with a remote peer
308 * split between service->service and client->service for simplicity
310 static struct ServiceSession * from_client_tail;
313 * Head of our double linked list for service-requests sent to us.
314 * for all of these elements we help the requesting service in calculating a scalar product
315 * split between service->service and client->service for simplicity
317 static struct ServiceSession * from_service_head;
320 * Tail of our double linked list for service-requests sent to us.
321 * for all of these elements we help the requesting service in calculating a scalar product
322 * split between service->service and client->service for simplicity
324 static struct ServiceSession * from_service_tail;
327 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
329 static int do_shutdown;
331 ///////////////////////////////////////////////////////////////////////////////
333 ///////////////////////////////////////////////////////////////////////////////
337 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
342 gcry_sexp_t gen_params;
344 gcry_sexp_t tmp_sexp;
353 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
354 GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
355 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
358 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
359 gcry_sexp_release (gen_params);
361 // get n and d of our publickey as MPI
362 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
363 GNUNET_assert (tmp_sexp);
364 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
365 gcry_sexp_release (tmp_sexp);
366 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
367 GNUNET_assert (tmp_sexp);
368 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
369 gcry_sexp_release (tmp_sexp);
370 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
371 GNUNET_assert (tmp_sexp);
372 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
373 gcry_sexp_release (key);
375 tmp1 = gcry_mpi_new (0);
376 tmp2 = gcry_mpi_new (0);
377 gcd = gcry_mpi_new (0);
378 my_g = gcry_mpi_new (0);
379 my_mu = gcry_mpi_new (0);
380 my_nsquare = gcry_mpi_new (0);
381 my_lambda = gcry_mpi_new (0);
384 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
385 gcry_mpi_sub_ui (tmp1, p, 1);
386 gcry_mpi_sub_ui (tmp2, q, 1);
387 gcry_mpi_gcd (gcd, tmp1, tmp2);
388 gcry_mpi_set (my_lambda, tmp1);
389 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
390 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
393 gcry_mpi_mul (my_nsquare, my_n, my_n);
397 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
398 // g must be smaller than n^2
399 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
402 // g must have gcd == 1 with n^2
403 gcry_mpi_gcd (gcd, my_g, my_nsquare);
405 while (gcry_mpi_cmp_ui (gcd, 1));
407 // is this a valid g?
408 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
409 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
410 gcry_mpi_sub_ui (tmp1, tmp1, 1);
411 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
412 gcry_mpi_gcd (gcd, tmp1, my_n);
414 while (gcry_mpi_cmp_ui (gcd, 1));
416 // calculate our mu based on g and n.
417 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
418 gcry_mpi_invm (my_mu, tmp1, my_n);
420 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
421 "(public-key (paillier (n %M)(g %M)))",
424 // get the length of this sexpression
425 my_pubkey_external_length = gcry_sexp_sprint (key,
430 GNUNET_assert (my_pubkey_external_length > 0);
431 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
433 // convert the sexpression to canonical format
434 gcry_sexp_sprint (key,
437 my_pubkey_external_length);
439 gcry_sexp_release (key);
441 // offset has to be sufficiently small to allow computation of:
442 // m1+m2 mod n == (S + a) + (S + b) mod n,
443 // if we have more complex operations, this factor needs to be lowered
444 my_offset = gcry_mpi_new (KEYBITS / 3);
445 gcry_mpi_set_bit (my_offset, KEYBITS / 3);
447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
452 * If target != size, move target bytes to the
453 * end of the size-sized buffer and zero out the
454 * first target-size bytes.
456 * @param buf original buffer
457 * @param size number of bytes in the buffer
458 * @param target target size of the buffer
461 adjust (unsigned char *buf, size_t size, size_t target)
464 memmove (&buf[target - size], buf, size);
465 memset (buf, 0, target - size);
471 * Encrypts an element using the paillier crypto system
473 * @param c ciphertext (output)
475 * @param g the public base
476 * @param n the module from which which r is chosen (Z*_n)
477 * @param n_square the module for encryption, for performance reasons.
480 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
484 GNUNET_assert (tmp = gcry_mpi_new (0));
486 while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
487 gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
488 // r must be 1 < r < n
491 gcry_mpi_powm (c, g, m, n_square);
492 gcry_mpi_powm (tmp, tmp, n, n_square);
493 gcry_mpi_mulm (c, tmp, c, n_square);
495 gcry_mpi_release (tmp);
500 * decrypts an element using the paillier crypto system
502 * @param m plaintext (output)
503 * @param c the ciphertext
504 * @param mu the modifier to correct encryption
505 * @param lambda the private exponent
506 * @param n the outer module for decryption
507 * @param n_square the inner module for decryption
510 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)
512 gcry_mpi_powm (m, c, lambda, n_square);
513 gcry_mpi_sub_ui (m, m, 1);
514 gcry_mpi_div (m, NULL, m, n, 0);
515 gcry_mpi_mulm (m, m, mu, n);
520 * computes the square sum over a vector of a given length.
522 * @param vector the vector to encrypt
523 * @param length the length of the vector
524 * @return an MPI value containing the calculated sum, never NULL
527 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
533 GNUNET_assert (sum = gcry_mpi_new (0));
534 GNUNET_assert (elem = gcry_mpi_new (0));
536 // calculare E(sum (ai ^ 2), publickey)
537 for (i = 0; i < length; i++) {
538 gcry_mpi_mul (elem, vector[i], vector[i]);
539 gcry_mpi_add (sum, sum, elem);
541 gcry_mpi_release (elem);
547 * Primitive callback for copying over a message, as they
548 * usually are too complex to be handled in the callback itself.
549 * clears a session-callback, if a session was handed over and the transmit handle was stored
551 * @param cls the message object
552 * @param size the size of the buffer we got
553 * @param buf the buffer to copy the message to
554 * @return 0 if we couldn't copy, else the size copied over
557 do_send_message (void *cls, size_t size, void *buf)
559 struct ServiceSession * session = cls;
564 if (ntohs (session->msg->size) != size)
570 type = ntohs (session->msg->type);
571 memcpy (buf, session->msg, size);
572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
573 "Sent a message of type %hu.\n",
575 GNUNET_free (session->msg);
580 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
581 session->state = FINALIZED;
582 session->client_transmit_handle = NULL;
585 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
586 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
587 session->service_transmit_handle = NULL;
588 if (session->state == WAITING_FOR_MULTIPART_TRANSMISSION)
589 prepare_service_request_multipart (session);
592 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
593 case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
594 session->service_transmit_handle = NULL;
595 if (session->state == WAITING_FOR_MULTIPART_TRANSMISSION)
596 prepare_service_response_multipart (session);
607 * initializes a new vector with fresh MPI values (=0) of a given length
609 * @param length of the vector to create
610 * @return the initialized vector, never NULL
613 initialize_mpi_vector (uint32_t length)
616 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
618 for (i = 0; i < length; i++)
619 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
624 * permutes an MPI vector according to the given permutation vector
626 * @param vector the vector to permuted
627 * @param perm the permutation to use
628 * @param length the length of the vectors
629 * @return the permuted vector (same as input), never NULL
632 permute_vector (gcry_mpi_t * vector,
636 gcry_mpi_t tmp[length];
639 GNUNET_assert (length > 0);
642 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
644 // permute vector according to given
645 for (i = 0; i < length; i++)
646 vector[i] = tmp[perm[i]];
653 * Finds a not terminated client/service session in the
654 * given DLL based on session key, element count and state.
656 * @param tail - the tail of the DLL
657 * @param key - the key we want to search for
658 * @param element_count - the total element count of the dataset (session->total)
659 * @param state - a pointer to the state the session should be in, NULL to ignore
660 * @param peerid - a pointer to the peer ID of the associated peer, NULL to ignore
661 * @return a pointer to a matching session, or NULL
663 static struct ServiceSession *
664 find_matching_session (struct ServiceSession * tail,
665 const struct GNUNET_HashCode * key,
666 uint32_t element_count,
667 enum SessionState * state,
668 const struct GNUNET_PeerIdentity * peerid)
670 struct ServiceSession * curr;
672 for (curr = tail; NULL != curr; curr = curr->prev) {
673 // if the key matches, and the element_count is same
674 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
675 && (curr->total == element_count)) {
676 // if incoming state is NULL OR is same as state of the queued request
677 if ((NULL == state) || (curr->state == *state)) {
678 // if peerid is NULL OR same as the peer Id in the queued request
680 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
681 // matches and is not an already terminated session
692 * Safely frees ALL memory areas referenced by a session.
694 * @param session - the session to free elements from
697 free_session_variables (struct ServiceSession * session)
702 for (i = 0; i < session->used; i++)
703 if (session->a[i]) gcry_mpi_release (session->a[i]);
704 GNUNET_free (session->a);
706 GNUNET_free_non_null (session->mask);
708 for (i = 0; i < session->used; i++)
709 if (session->r[i]) gcry_mpi_release (session->r[i]);
710 GNUNET_free(session->r);
712 if (session->r_prime){
713 for (i = 0; i < session->used; i++)
714 if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
715 GNUNET_free(session->r_prime);
718 gcry_mpi_release (session->s);
719 if (session->s_prime)
720 gcry_mpi_release (session->s_prime);
721 if (session->product)
722 gcry_mpi_release (session->product);
724 if (session->remote_pubkey)
725 gcry_sexp_release (session->remote_pubkey);
727 GNUNET_free_non_null (session->vector);
729 ///////////////////////////////////////////////////////////////////////////////
730 // Event and Message Handlers
731 ///////////////////////////////////////////////////////////////////////////////
734 * A client disconnected.
736 * Remove the associated session(s), release data structures
737 * and cancel pending outgoing transmissions to the client.
738 * if the session has not yet completed, we also cancel Alice's request to Bob.
740 * @param cls closure, NULL
741 * @param client identification of the client
744 handle_client_disconnect (void *cls,
745 struct GNUNET_SERVER_Client *client)
747 struct ServiceSession *session;
751 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
754 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755 _ ("Client (%p) disconnected from us.\n"), client);
756 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
758 if (!(session->role == BOB && session->state == FINALIZED)) {
759 //we MUST terminate any client message underway
760 if (session->service_transmit_handle && session->tunnel)
761 GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
762 if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
763 GNUNET_MESH_tunnel_destroy (session->tunnel);
765 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
766 GNUNET_SCHEDULER_cancel (session->client_notification_task);
767 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
769 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
770 GNUNET_SCHEDULER_cancel (session->service_request_task);
771 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
773 if (NULL != session->client_transmit_handle) {
774 GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
775 session->client_transmit_handle = NULL;
777 free_session_variables (session);
778 GNUNET_free (session);
783 * Notify the client that the session has succeeded or failed completely.
784 * This message gets sent to
785 * * alice's client if bob disconnected or to
786 * * bob's client if the operation completed or alice disconnected
788 * @param cls the associated client session
789 * @param tc the task context handed to us by the scheduler, unused
792 prepare_client_end_notification (void * cls,
793 const struct GNUNET_SCHEDULER_TaskContext * tc)
795 struct ServiceSession * session = cls;
796 struct GNUNET_SCALARPRODUCT_client_response * msg;
798 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
800 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
801 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
802 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
803 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
804 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
805 // signal error if not signalized, positive result-range field but zero length.
806 msg->product_length = htonl (0);
807 msg->range = (session->state == FINALIZED) ? 0 : -1;
809 session->msg = &msg->header;
811 //transmit this message to our client
812 session->client_transmit_handle =
813 GNUNET_SERVER_notify_transmit_ready (session->client,
814 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
815 GNUNET_TIME_UNIT_FOREVER_REL,
819 // if we could not even queue our request, something is wrong
820 if (NULL == session->client_transmit_handle) {
821 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
822 // usually gets freed by do_send_message
827 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
833 * Send a multi part chunk of a service response from bob to alice.
834 * This element only contains the two permutations of R, R'.
836 * @param cls the associated service session
839 prepare_service_response_multipart (void *cls)
841 struct ServiceSession * session = cls;
842 unsigned char * current;
843 unsigned char * element_exported;
844 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
848 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
850 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
851 todo_count = session->used - session->transferred;
853 if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
854 // send the currently possible maximum chunk, we always transfer both permutations
855 todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
857 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
858 msg = GNUNET_malloc (msg_length);
859 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
860 msg->header.size = htons (msg_length);
861 msg->multipart_element_count = htonl (todo_count);
863 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
864 current = (unsigned char *) &msg[1];
866 for (i = session->transferred; i < session->transferred + todo_count; i++) {
868 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
869 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
870 element_exported, PAILLIER_ELEMENT_LENGTH,
873 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
874 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
875 current += PAILLIER_ELEMENT_LENGTH;
877 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
878 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
879 element_exported, PAILLIER_ELEMENT_LENGTH,
881 session->r_prime[i]));
882 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
883 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
884 current += PAILLIER_ELEMENT_LENGTH;
886 GNUNET_free (element_exported);
887 for (i = session->transferred; i < session->transferred; i++) {
888 gcry_mpi_release (session->r_prime[i]);
889 gcry_mpi_release (session->r[i]);
891 session->transferred += todo_count;
892 session->msg = (struct GNUNET_MessageHeader *) msg;
893 session->service_transmit_handle =
894 GNUNET_MESH_notify_transmit_ready (session->tunnel,
896 GNUNET_TIME_UNIT_FOREVER_REL,
900 //disconnect our client
901 if (NULL == session->service_transmit_handle) {
902 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
903 session->state = FINALIZED;
905 session->response->client_notification_task =
906 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
910 if (session->transferred != session->used)
912 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
915 session->state = FINALIZED;
920 * generates the response message to be sent to alice after computing
921 * the values (1), (2), S and S'
922 * (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)})$
923 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
924 * S: $S := E_A(sum (r_i + b_i)^2)$
925 * S': $S' := E_A(sum r_i^2)$
927 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
928 * @param s_prime S': $S' := E_A(sum r_i^2)$
929 * @param session the associated requesting session with alice
930 * @return GNUNET_NO if we could not send our message
931 * GNUNET_OK if the operation succeeded
934 prepare_service_response (gcry_mpi_t s,
936 struct ServiceSession * session)
938 struct GNUNET_SCALARPRODUCT_service_response * msg;
939 uint32_t msg_length = 0;
940 unsigned char * current = NULL;
941 unsigned char * element_exported = NULL;
942 size_t element_length = 0;
945 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
946 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
948 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used * PAILLIER_ELEMENT_LENGTH) { //kp, kq
949 msg_length += +2 * session->used * PAILLIER_ELEMENT_LENGTH;
950 session->transferred = session->used;
953 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
956 msg = GNUNET_malloc (msg_length);
958 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
959 msg->header.size = htons (msg_length);
960 msg->total_element_count = htonl (session->total);
961 msg->contained_element_count = htonl (session->used);
962 msg->contained_element_count = htonl (session->transferred);
963 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
964 current = (unsigned char *) &msg[1];
966 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
967 // 4 times the same logics with slight variations.
968 // doesn't really justify having 2 functions for that
969 // so i put it into blocks to enhance readability
971 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
972 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
973 element_exported, PAILLIER_ELEMENT_LENGTH,
976 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
977 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
978 current += PAILLIER_ELEMENT_LENGTH;
981 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
982 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
983 element_exported, PAILLIER_ELEMENT_LENGTH,
986 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
987 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
988 current += PAILLIER_ELEMENT_LENGTH;
991 for (i = 0; i < session->transferred; i++) {
993 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
994 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
995 element_exported, PAILLIER_ELEMENT_LENGTH,
998 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
999 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1000 current += PAILLIER_ELEMENT_LENGTH;
1002 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1003 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1004 element_exported, PAILLIER_ELEMENT_LENGTH,
1006 session->r_prime[i]));
1007 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1008 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1009 current += PAILLIER_ELEMENT_LENGTH;
1012 GNUNET_free (element_exported);
1013 for (i = 0; i < session->transferred; i++) {
1014 gcry_mpi_release (session->r_prime[i]);
1015 gcry_mpi_release (session->r[i]);
1017 gcry_mpi_release (s);
1018 gcry_mpi_release (s_prime);
1020 session->msg = (struct GNUNET_MessageHeader *) msg;
1021 session->service_transmit_handle =
1022 GNUNET_MESH_notify_transmit_ready (session->tunnel,
1024 GNUNET_TIME_UNIT_FOREVER_REL,
1028 //disconnect our client
1029 if (NULL == session->service_transmit_handle) {
1030 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1031 session->state = FINALIZED;
1033 session->response->client_notification_task =
1034 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1038 if (session->transferred != session->used)
1040 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1043 session->state = FINALIZED;
1050 * compute the values
1051 * (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)})$
1052 * (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1053 * S: $S := E_A(\sum (r_i + b_i)^2)$
1054 * S': $S' := E_A(\sum r_i^2)$
1056 * @param request the requesting session + bob's requesting peer
1057 * @param response the responding session + bob's client handle
1058 * @return GNUNET_SYSERR if the computation failed
1059 * GNUNET_OK if everything went well.
1062 compute_service_response (struct ServiceSession * request,
1063 struct ServiceSession * response)
1067 int ret = GNUNET_SYSERR;
1071 gcry_mpi_t * rand = NULL;
1072 gcry_mpi_t * r = NULL;
1073 gcry_mpi_t * r_prime = NULL;
1076 gcry_mpi_t * a_pi_prime;
1078 gcry_mpi_t * rand_pi;
1079 gcry_mpi_t * rand_pi_prime;
1080 gcry_mpi_t s = NULL;
1081 gcry_mpi_t s_prime = NULL;
1082 gcry_mpi_t remote_n = NULL;
1083 gcry_mpi_t remote_nsquare;
1084 gcry_mpi_t remote_g = NULL;
1085 gcry_sexp_t tmp_exp;
1088 count = request->used;
1090 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1091 a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1092 b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1093 a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1094 rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1095 rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1097 // convert responder session to from long to mpi
1098 for (i = 0, j = 0; i < response->total && j < count; i++) {
1099 if (request->mask[i / 8] & (1 << (i % 8))) {
1100 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1101 // long to gcry_mpi_t
1102 if (0 > response->vector[i]) {
1103 b[j] = gcry_mpi_new (0);
1104 gcry_mpi_sub_ui (b[j], b[j], value);
1107 b[j] = gcry_mpi_set_ui (NULL, value);
1112 GNUNET_free (response->vector);
1113 response->vector = NULL;
1115 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1117 GNUNET_break_op (0);
1118 gcry_sexp_release (request->remote_pubkey);
1119 request->remote_pubkey = NULL;
1122 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1125 gcry_sexp_release (tmp_exp);
1128 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1129 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1130 gcry_sexp_release (tmp_exp);
1131 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1132 gcry_sexp_release (request->remote_pubkey);
1133 request->remote_pubkey = NULL;
1135 GNUNET_break_op (0);
1136 gcry_mpi_release (remote_n);
1139 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1142 gcry_mpi_release (remote_n);
1143 gcry_sexp_release (tmp_exp);
1146 gcry_sexp_release (tmp_exp);
1148 // generate r, p and q
1149 rand = initialize_mpi_vector (count);
1150 for (i = 0; i < count; i++) {
1151 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
1153 // long to gcry_mpi_t
1155 gcry_mpi_sub_ui (rand[i],
1159 rand[i] = gcry_mpi_set_ui (rand[i], value);
1161 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1162 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1163 //initialize the result vectors
1164 r = initialize_mpi_vector (count);
1165 r_prime = initialize_mpi_vector (count);
1167 // copy the REFERNCES of a, b and r into aq and bq. we will not change
1168 // those values, thus we can work with the references
1169 memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1170 memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1171 memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1172 memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1173 memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1175 // generate p and q permutations for a, b and r
1176 GNUNET_assert (permute_vector (a_pi, p, count));
1177 GNUNET_assert (permute_vector (b_pi, p, count));
1178 GNUNET_assert (permute_vector (rand_pi, p, count));
1179 GNUNET_assert (permute_vector (a_pi_prime, q, count));
1180 GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1182 // encrypt the element
1183 // for the sake of readability I decided to have dedicated permutation
1184 // vectors, which get rid of all the lookups in p/q.
1185 // however, ap/aq are not absolutely necessary but are just abstraction
1186 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1187 for (i = 0; i < count; i++) {
1188 // E(S - r_pi - b_pi)
1189 gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1190 gcry_mpi_sub (r[i], r[i], b_pi[i]);
1191 encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1193 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
1194 gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1198 GNUNET_free (rand_pi);
1200 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1201 for (i = 0; i < count; i++) {
1203 gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1204 encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1206 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1207 gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1209 GNUNET_free (a_pi_prime);
1210 GNUNET_free (rand_pi_prime);
1213 request->r_prime = r_prime;
1214 request->response = response;
1216 // Calculate S' = E(SUM( r_i^2 ))
1217 s_prime = compute_square_sum (rand, count);
1218 encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1220 // Calculate S = E(SUM( (r_i + b_i)^2 ))
1221 for (i = 0; i < count; i++) {
1222 gcry_mpi_add (rand[i], rand[i], b[i]);
1224 s = compute_square_sum (rand, count);
1225 encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1226 gcry_mpi_release (remote_n);
1227 gcry_mpi_release (remote_g);
1228 gcry_mpi_release (remote_nsquare);
1230 // release r and tmp
1231 for (i = 0; i < count; i++)
1232 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1233 gcry_mpi_release (rand[i]);
1235 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1236 if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1237 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1238 GNUNET_i2s (&request->peer));
1243 for (i = 0; i < count; i++) {
1244 gcry_mpi_release (b[i]);
1245 gcry_mpi_release (request->a[i]);
1249 GNUNET_free (request->a);
1257 * Send a multi part chunk of a service request from alice to bob.
1258 * This element only contains a part of the elements-vector (session->a[]),
1259 * mask and public key set have to be contained within the first message
1261 * This allows a ~32kbit key length while using 32000 elements or 62000 elements per request.
1263 * @param cls the associated service session
1266 prepare_service_request_multipart (void *cls)
1268 struct ServiceSession * session = cls;
1269 unsigned char * current;
1270 unsigned char * element_exported;
1271 struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1274 uint32_t msg_length;
1275 uint32_t todo_count;
1276 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1280 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1281 todo_count = session->used - session->transferred;
1283 if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1284 // send the currently possible maximum chunk
1285 todo_count = MULTIPART_ELEMENT_CAPACITY;
1287 msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1288 msg = GNUNET_malloc (msg_length);
1289 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1290 msg->header.size = htons (msg_length);
1291 msg->multipart_element_count = htonl (todo_count);
1293 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1294 a = gcry_mpi_new (KEYBITS * 2);
1295 current = (unsigned char *) &msg[1];
1296 // encrypt our vector and generate string representations
1297 for (i = session->last_processed, j = 0; i < session->total; i++) {
1298 // is this a used element?
1299 if (session->mask[i / 8] & 1 << (i % 8)) {
1300 if (todo_count <= j)
1301 break; //reached end of this message, can't include more
1303 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1304 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1306 a = gcry_mpi_set_ui (a, 0);
1307 // long to gcry_mpi_t
1308 if (session->vector[i] < 0)
1309 gcry_mpi_sub_ui (a, a, value);
1311 gcry_mpi_add_ui (a, a, value);
1313 session->a[session->transferred + j++] = gcry_mpi_set (NULL, a);
1314 gcry_mpi_add (a, a, my_offset);
1315 encrypt_element (a, a, my_g, my_n, my_nsquare);
1317 // get representation as string
1318 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1319 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1320 element_exported, PAILLIER_ELEMENT_LENGTH,
1324 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1325 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1327 // copy over to the message
1328 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1329 current += PAILLIER_ELEMENT_LENGTH;
1332 gcry_mpi_release (a);
1333 GNUNET_free (element_exported);
1334 session->transferred += todo_count;
1336 session->msg = (struct GNUNET_MessageHeader *) msg;
1337 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1339 //transmit via mesh messaging
1340 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1341 GNUNET_TIME_UNIT_FOREVER_REL,
1345 if (!session->service_transmit_handle) {
1346 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1348 session->msg = NULL;
1349 session->client_notification_task =
1350 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1354 if (session->transferred != session->used) {
1355 session->last_processed = i;
1359 session->state = WAITING_FOR_SERVICE_RESPONSE;
1363 * Executed by Alice, fills in a service-request message and sends it to the given peer
1365 * @param session the session associated with this request, then also holds the CORE-handle
1366 * @return #GNUNET_SYSERR if we could not send the message
1367 * #GNUNET_NO if the message was too large
1368 * #GNUNET_OK if we sent it
1371 prepare_service_request (void *cls,
1372 const struct GNUNET_SCHEDULER_TaskContext *tc)
1374 struct ServiceSession * session = cls;
1375 unsigned char * current;
1376 unsigned char * element_exported;
1377 struct GNUNET_SCALARPRODUCT_service_request * msg;
1380 uint32_t msg_length;
1381 size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1385 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1389 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1390 +session->mask_length
1391 + my_pubkey_external_length;
1393 if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used * PAILLIER_ELEMENT_LENGTH) {
1394 msg_length += session->used * PAILLIER_ELEMENT_LENGTH;
1395 session->transferred = session->used;
1398 //create a multipart msg, first we calculate a new msg size for the head msg
1399 session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1402 msg = GNUNET_malloc (msg_length);
1403 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1404 msg->total_element_count = htonl (session->used);
1405 msg->contained_element_count = htonl (session->transferred);
1406 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1407 msg->mask_length = htonl (session->mask_length);
1408 msg->pk_length = htonl (my_pubkey_external_length);
1409 msg->element_count = htonl (session->total);
1410 msg->header.size = htons (msg_length);
1412 // fill in the payload
1413 current = (unsigned char *) &msg[1];
1414 // copy over the mask
1415 memcpy (current, session->mask, session->mask_length);
1416 // copy over our public key
1417 current += session->mask_length;
1418 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1419 current += my_pubkey_external_length;
1421 // now copy over the element vector
1422 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1423 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
1424 a = gcry_mpi_new (KEYBITS * 2);
1425 // encrypt our vector and generate string representations
1426 for (i = 0, j = 0; i < session->total; i++) {
1427 // if this is a used element...
1428 if (session->mask[i / 8] & 1 << (i % 8)) {
1429 if (session->transferred <= j)
1430 break; //reached end of this message, can't include more
1432 memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1433 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1435 a = gcry_mpi_set_ui (a, 0);
1436 // long to gcry_mpi_t
1437 if (session->vector[i] < 0)
1438 gcry_mpi_sub_ui (a, a, value);
1440 gcry_mpi_add_ui (a, a, value);
1442 session->a[j++] = gcry_mpi_set (NULL, a);
1443 gcry_mpi_add (a, a, my_offset);
1444 encrypt_element (a, a, my_g, my_n, my_nsquare);
1446 // get representation as string
1447 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1448 GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1449 element_exported, PAILLIER_ELEMENT_LENGTH,
1453 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1454 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1456 // copy over to the message
1457 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1458 current += PAILLIER_ELEMENT_LENGTH;
1461 gcry_mpi_release (a);
1462 GNUNET_free (element_exported);
1464 session->msg = (struct GNUNET_MessageHeader *) msg;
1465 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1467 //transmit via mesh messaging
1468 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1469 GNUNET_TIME_UNIT_FOREVER_REL,
1473 if (!session->service_transmit_handle) {
1474 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1476 session->msg = NULL;
1477 session->client_notification_task =
1478 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1482 if (session->transferred != session->used) {
1483 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1484 session->last_processed = i;
1487 //singlepart message
1488 session->state = WAITING_FOR_SERVICE_RESPONSE;
1492 * Handler for a client request message.
1493 * Can either be type A or B
1494 * A: request-initiation to compute a scalar product with a peer
1495 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1497 * @param cls closure
1498 * @param client identification of the client
1499 * @param message the actual message
1502 handle_client_request (void *cls,
1503 struct GNUNET_SERVER_Client *client,
1504 const struct GNUNET_MessageHeader *message)
1506 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1507 struct ServiceSession * session;
1508 uint32_t element_count;
1509 uint32_t mask_length;
1514 // only one concurrent session per client connection allowed, simplifies logics a lot...
1515 session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1516 if ((NULL != session) && (session->state != FINALIZED)) {
1517 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1520 else if (NULL != session) {
1521 // old session is already completed, clean it up
1522 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1523 free_session_variables (session);
1524 GNUNET_free (session);
1527 //we need at least a peer and one message id to compare
1528 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1529 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1530 _ ("Too short message received from client!\n"));
1531 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1535 msg_type = ntohs (msg->header.type);
1536 element_count = ntohl (msg->element_count);
1537 mask_length = ntohl (msg->mask_length);
1539 //sanity check: is the message as long as the message_count fields suggests?
1540 if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1541 || (0 == element_count)) {
1542 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1543 _ ("Invalid message received from client, session information incorrect!\n"));
1544 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1548 // do we have a duplicate session here already?
1549 if (NULL != find_matching_session (from_client_tail,
1553 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1554 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1555 GNUNET_h2s (&msg->key));
1556 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1560 session = GNUNET_new (struct ServiceSession);
1561 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1562 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1563 session->client = client;
1564 session->total = element_count;
1565 session->mask_length = mask_length;
1566 // get our transaction key
1567 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1568 //allocate memory for vector and encrypted vector
1569 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1570 vector = (int32_t *) & msg[1];
1572 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1573 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1575 GNUNET_h2s (&session->key));
1577 session->role = ALICE;
1579 session->mask = GNUNET_malloc (mask_length);
1580 memcpy (session->mask, &vector[element_count], mask_length);
1582 // copy over the elements
1584 for (i = 0; i < element_count; i++) {
1585 session->vector[i] = ntohl (vector[i]);
1586 if (session->vector[i] == 0)
1587 session->mask[i / 8] &= ~(1 << (i % 8));
1588 if (session->mask[i / 8] & (1 << (i % 8)))
1592 if (0 == session->used) {
1593 GNUNET_break_op (0);
1594 GNUNET_free (session->vector);
1595 GNUNET_free (session);
1596 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1599 //session with ourself makes no sense!
1600 if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1602 GNUNET_free (session->vector);
1603 GNUNET_free (session);
1604 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1608 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1609 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1610 _ ("Creating new tunnel to for session with key %s.\n"),
1611 GNUNET_h2s (&session->key));
1612 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1614 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1617 //prepare_service_request, tunnel_peer_disconnect_handler,
1618 if (!session->tunnel) {
1620 GNUNET_free (session->vector);
1621 GNUNET_free (session);
1622 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1625 GNUNET_SERVER_client_set_user_context (client, session);
1626 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1628 session->state = CLIENT_REQUEST_RECEIVED;
1629 session->service_request_task =
1630 GNUNET_SCHEDULER_add_now (&prepare_service_request,
1635 struct ServiceSession * requesting_session;
1636 enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1638 session->role = BOB;
1639 session->mask = NULL;
1640 // copy over the elements
1641 session->used = element_count;
1642 for (i = 0; i < element_count; i++)
1643 session->vector[i] = ntohl (vector[i]);
1644 session->state = CLIENT_RESPONSE_RECEIVED;
1646 GNUNET_SERVER_client_set_user_context (client, session);
1647 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1649 //check if service queue contains a matching request
1650 requesting_session = find_matching_session (from_service_tail,
1653 &needed_state, NULL);
1654 if (NULL != requesting_session) {
1655 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));
1656 if (GNUNET_OK != compute_service_response (requesting_session, session))
1657 session->client_notification_task =
1658 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1663 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));
1664 // no matching session exists yet, store the response
1665 // for later processing by handle_service_request()
1668 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1673 * Function called for inbound tunnels.
1675 * @param cls closure
1676 * @param tunnel new handle to the tunnel
1677 * @param initiator peer that started the tunnel
1678 * @param atsi performance information for the tunnel
1679 * @return initial tunnel context for the tunnel
1680 * (can be NULL -- that's not an error)
1683 tunnel_incoming_handler (void *cls,
1684 struct GNUNET_MESH_Tunnel *tunnel,
1685 const struct GNUNET_PeerIdentity *initiator,
1688 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1690 c->peer = *initiator;
1693 c->state = WAITING_FOR_SERVICE_REQUEST;
1699 * Function called whenever a tunnel is destroyed. Should clean up
1700 * any associated state.
1702 * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1704 * @param cls closure (set from GNUNET_MESH_connect)
1705 * @param tunnel connection to the other end (henceforth invalid)
1706 * @param tunnel_ctx place where local state associated
1707 * with the tunnel is stored
1710 tunnel_destruction_handler (void *cls,
1711 const struct GNUNET_MESH_Tunnel *tunnel,
1714 struct ServiceSession * session = tunnel_ctx;
1715 struct ServiceSession * client_session;
1716 struct ServiceSession * curr;
1718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719 _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1720 GNUNET_h2s (&session->key),
1721 GNUNET_i2s (&session->peer));
1722 if (ALICE == session->role) {
1723 // as we have only one peer connected in each session, just remove the session
1725 if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1726 session->tunnel = NULL;
1727 // if this happened before we received the answer, we must terminate the session
1728 session->client_notification_task =
1729 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1733 else { //(BOB == session->role) service session
1734 // remove the session, unless it has already been dequeued, but somehow still active
1735 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1736 // scenario: disconnect before alice can send her message to bob.
1737 for (curr = from_service_head; NULL != curr; curr = curr->next)
1738 if (curr == session) {
1739 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1742 // there is a client waiting for this service session, terminate it, too!
1743 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1744 client_session = find_matching_session (from_client_tail,
1748 free_session_variables (session);
1749 GNUNET_free (session);
1751 // the client has to check if it was waiting for a result
1752 // or if it was a responder, no point in adding more statefulness
1753 if (client_session && (!do_shutdown)) {
1754 client_session->state = FINALIZED;
1755 client_session->client_notification_task =
1756 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1764 * Compute our scalar product, done by Alice
1766 * @param session - the session associated with this computation
1767 * @return product as MPI, never NULL
1770 compute_scalar_product (struct ServiceSession * session)
1781 count = session->used;
1782 tmp = gcry_mpi_new (KEYBITS);
1783 // due to the introduced static offset S, we now also have to remove this
1784 // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1785 // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1786 for (i = 0; i < count; i++) {
1787 decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1788 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1789 gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1790 decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1791 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1792 gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1795 // calculate t = sum(ai)
1796 t = compute_square_sum (session->a, count);
1799 u = gcry_mpi_new (0);
1800 tmp = compute_square_sum (session->r, count);
1801 gcry_mpi_sub (u, u, tmp);
1802 gcry_mpi_release (tmp);
1805 utick = gcry_mpi_new (0);
1806 tmp = compute_square_sum (session->r_prime, count);
1807 gcry_mpi_sub (utick, utick, tmp);
1809 GNUNET_assert (p = gcry_mpi_new (0));
1810 GNUNET_assert (ptick = gcry_mpi_new (0));
1813 decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1814 decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1817 gcry_mpi_add (p, session->s, t);
1818 gcry_mpi_add (p, p, u);
1821 gcry_mpi_add (ptick, session->s_prime, t);
1822 gcry_mpi_add (ptick, ptick, utick);
1824 gcry_mpi_release (t);
1825 gcry_mpi_release (u);
1826 gcry_mpi_release (utick);
1829 gcry_mpi_sub (p, p, ptick);
1830 gcry_mpi_release (ptick);
1831 tmp = gcry_mpi_set_ui (tmp, 2);
1832 gcry_mpi_div (p, NULL, p, tmp, 0);
1834 gcry_mpi_release (tmp);
1835 for (i = 0; i < count; i++)
1836 gcry_mpi_release (session->a[i]);
1837 GNUNET_free (session->a);
1844 * prepare the response we will send to alice or bobs' clients.
1845 * in Bobs case the product will be NULL.
1847 * @param session the session associated with our client.
1850 prepare_client_response (void *cls,
1851 const struct GNUNET_SCHEDULER_TaskContext *tc)
1853 struct ServiceSession * session = cls;
1854 struct GNUNET_SCALARPRODUCT_client_response * msg;
1855 unsigned char * product_exported = NULL;
1856 size_t product_length = 0;
1857 uint32_t msg_length = 0;
1862 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1864 if (session->product) {
1865 gcry_mpi_t value = gcry_mpi_new (0);
1867 sign = gcry_mpi_cmp_ui (session->product, 0);
1868 // libgcrypt can not handle a print of a negative number
1869 // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1871 gcry_mpi_sub (value, value, session->product);
1873 else if (0 < sign) {
1875 gcry_mpi_add (value, value, session->product);
1880 gcry_mpi_release (session->product);
1881 session->product = NULL;
1883 // get representation as string
1885 && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1889 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1891 range = -1; // signal error with product-length = 0 and range = -1
1893 gcry_mpi_release (value);
1896 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1897 msg = GNUNET_malloc (msg_length);
1898 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1899 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1900 if (product_exported != NULL) {
1901 memcpy (&msg[1], product_exported, product_length);
1902 GNUNET_free (product_exported);
1904 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1905 msg->header.size = htons (msg_length);
1907 msg->product_length = htonl (product_length);
1909 session->msg = (struct GNUNET_MessageHeader *) msg;
1910 //transmit this message to our client
1911 session->client_transmit_handle =
1912 GNUNET_SERVER_notify_transmit_ready (session->client,
1914 GNUNET_TIME_UNIT_FOREVER_REL,
1917 if (NULL == session->client_transmit_handle) {
1918 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1919 _ ("Could not send message to client (%p)!\n"),
1921 session->client = NULL;
1922 // callback was not called!
1924 session->msg = NULL;
1927 // gracefully sent message, just terminate session structure
1928 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1929 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1931 GNUNET_h2s (&session->key));
1935 * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1937 * @param cls closure (set from #GNUNET_MESH_connect)
1938 * @param tunnel connection to the other end
1939 * @param tunnel_ctx place to store local state associated with the tunnel
1940 * @param sender who sent the message
1941 * @param message the actual message
1942 * @param atsi performance data for the connection
1943 * @return #GNUNET_OK to keep the connection open,
1944 * #GNUNET_SYSERR to close it (signal serious error)
1947 handle_service_request_multipart (void *cls,
1948 struct GNUNET_MESH_Tunnel * tunnel,
1950 const struct GNUNET_MessageHeader * message)
1952 struct ServiceSession * session;
1953 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1954 uint32_t used_elements;
1955 uint32_t contained_elements=0;
1956 uint32_t msg_length;
1957 unsigned char * current;
1961 // are we in the correct state?
1962 session = (struct ServiceSession *) * tunnel_ctx;
1963 if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
1966 // shorter than minimum?
1967 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1970 used_elements = session->used;
1971 contained_elements = ntohl (msg->multipart_element_count);
1972 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1973 + contained_elements * PAILLIER_ELEMENT_LENGTH;
1975 if (( ntohs (msg->header.size) != msg_length)
1976 || (used_elements < contained_elements + session->transferred)) {
1979 current = (unsigned char *) &msg[1];
1980 if (contained_elements != 0) {
1981 // Convert each vector element to MPI_value
1982 for (i = session->transferred; i < session->transferred+contained_elements; i++) {
1984 if (0 != (rc = gcry_mpi_scan (&session->a[i],
1986 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1987 PAILLIER_ELEMENT_LENGTH,
1989 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1993 session->transferred+=contained_elements;
1995 if (session->transferred == used_elements) {
1996 // single part finished
1997 session->state = SERVICE_REQUEST_RECEIVED;
1998 if (session->response) {
1999 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2000 if (GNUNET_OK != compute_service_response (session, session->response)) {
2001 //something went wrong, remove it again...
2006 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2009 // multipart message
2015 // and notify our client-session that we could not complete the session
2016 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2017 if (session->response)
2018 // we just found the responder session in this queue
2019 session->response->client_notification_task =
2020 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2022 free_session_variables (session);
2023 GNUNET_free (session);
2024 return GNUNET_SYSERR;
2028 * Handle a request from another service to calculate a scalarproduct with us.
2030 * @param cls closure (set from #GNUNET_MESH_connect)
2031 * @param tunnel connection to the other end
2032 * @param tunnel_ctx place to store local state associated with the tunnel
2033 * @param sender who sent the message
2034 * @param message the actual message
2035 * @param atsi performance data for the connection
2036 * @return #GNUNET_OK to keep the connection open,
2037 * #GNUNET_SYSERR to close it (signal serious error)
2040 handle_service_request (void *cls,
2041 struct GNUNET_MESH_Tunnel * tunnel,
2043 const struct GNUNET_MessageHeader * message)
2045 struct ServiceSession * session;
2046 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2047 uint32_t mask_length;
2049 uint32_t used_elements;
2050 uint32_t contained_elements = 0;
2051 uint32_t element_count;
2052 uint32_t msg_length;
2053 unsigned char * current;
2056 enum SessionState needed_state;
2058 session = (struct ServiceSession *) * tunnel_ctx;
2059 if (WAITING_FOR_SERVICE_REQUEST != session->state) {
2062 // Check if message was sent by me, which would be bad!
2063 if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2064 GNUNET_free (session);
2066 return GNUNET_SYSERR;
2068 // shorter than expected?
2069 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2070 GNUNET_free (session);
2071 GNUNET_break_op (0);
2072 return GNUNET_SYSERR;
2074 mask_length = ntohl (msg->mask_length);
2075 pk_length = ntohl (msg->pk_length);
2076 used_elements = ntohl (msg->total_element_count);
2077 contained_elements = ntohl (msg->contained_element_count);
2078 element_count = ntohl (msg->element_count);
2079 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2080 +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2082 //sanity check: is the message as long as the message_count fields suggests?
2083 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2084 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2086 GNUNET_free (session);
2087 GNUNET_break_op (0);
2088 return GNUNET_SYSERR;
2090 if (find_matching_session (from_service_tail,
2095 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2096 GNUNET_free (session);
2097 return GNUNET_SYSERR;
2100 memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2101 session->total = element_count;
2102 session->used = used_elements;
2103 session->transferred = contained_elements;
2104 session->tunnel = tunnel;
2107 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2108 current = (unsigned char *) &msg[1];
2109 //preserve the mask, we will need that later on
2110 session->mask = GNUNET_malloc (mask_length);
2111 memcpy (session->mask, current, mask_length);
2113 current += mask_length;
2115 //convert the publickey to sexp
2116 if (0 != (rc = gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))) {
2117 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_sexp_new", rc);
2118 GNUNET_free (session->mask);
2119 GNUNET_free (session);
2120 return GNUNET_SYSERR;
2122 current += pk_length;
2123 //check if service queue contains a matching request
2124 needed_state = CLIENT_RESPONSE_RECEIVED;
2125 session->response = find_matching_session (from_client_tail,
2128 &needed_state, NULL);
2130 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2131 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2132 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2133 if (contained_elements != 0) {
2134 // Convert each vector element to MPI_value
2135 for (i = 0; i < contained_elements; i++) {
2137 if (0 != (rc = gcry_mpi_scan (&session->a[i],
2139 ¤t[i * PAILLIER_ELEMENT_LENGTH],
2140 PAILLIER_ELEMENT_LENGTH,
2142 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2146 if (contained_elements == used_elements) {
2147 // single part finished
2148 session->state = SERVICE_REQUEST_RECEIVED;
2149 if (session->response) {
2150 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2151 if (GNUNET_OK != compute_service_response (session, session->response)) {
2152 //something went wrong, remove it again...
2157 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2160 // multipart message
2165 GNUNET_break_op (0);
2166 if ((NULL != session->next) || (NULL != session->prev) || (from_service_head == session))
2167 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2168 // and notify our client-session that we could not complete the session
2169 if (session->response)
2170 // we just found the responder session in this queue
2171 session->response->client_notification_task =
2172 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2174 free_session_variables (session);
2175 return GNUNET_SYSERR;
2179 * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2181 * @param cls closure (set from #GNUNET_MESH_connect)
2182 * @param tunnel connection to the other end
2183 * @param tunnel_ctx place to store local state associated with the tunnel
2184 * @param sender who sent the message
2185 * @param message the actual message
2186 * @param atsi performance data for the connection
2187 * @return #GNUNET_OK to keep the connection open,
2188 * #GNUNET_SYSERR to close it (signal serious error)
2191 handle_service_response_multipart (void *cls,
2192 struct GNUNET_MESH_Tunnel * tunnel,
2194 const struct GNUNET_MessageHeader * message)
2196 struct ServiceSession * session;
2197 const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2198 unsigned char * current;
2201 uint32_t contained=0;
2205 GNUNET_assert (NULL != message);
2206 // are we in the correct state?
2207 session = (struct ServiceSession *) * tunnel_ctx;
2208 if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2211 // shorter than minimum?
2212 if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2215 contained = ntohl (msg->multipart_element_count);
2216 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2217 + 2 * contained * PAILLIER_ELEMENT_LENGTH;
2218 //sanity check: is the message as long as the message_count fields suggests?
2219 if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2222 current = (unsigned char *) &msg[1];
2223 // Convert each k[][perm] to its MPI_value
2224 for (i = 0; i < contained; i++) {
2225 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2226 PAILLIER_ELEMENT_LENGTH, &read))) {
2227 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2230 current += PAILLIER_ELEMENT_LENGTH;
2231 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2232 PAILLIER_ELEMENT_LENGTH, &read))) {
2233 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2236 current += PAILLIER_ELEMENT_LENGTH;
2238 session->transferred += contained;
2239 if (session->transferred != session->used)
2241 session->state = SERVICE_RESPONSE_RECEIVED;
2242 session->product = compute_scalar_product (session);
2243 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2246 GNUNET_break_op (0);
2247 free_session_variables (session);
2248 session->state = FINALIZED;
2249 session->tunnel = NULL;
2250 // send message with product to client
2251 if (ALICE == session->role)
2252 session->client_notification_task =
2253 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2255 // the tunnel has done its job, terminate our connection and the tunnel
2256 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2257 // just close the connection, as recommended by Christian
2258 return GNUNET_SYSERR;
2262 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2264 * @param cls closure (set from #GNUNET_MESH_connect)
2265 * @param tunnel connection to the other end
2266 * @param tunnel_ctx place to store local state associated with the tunnel
2267 * @param sender who sent the message
2268 * @param message the actual message
2269 * @param atsi performance data for the connection
2270 * @return #GNUNET_OK to keep the connection open,
2271 * #GNUNET_SYSERR to close it (we are done)
2274 handle_service_response (void *cls,
2275 struct GNUNET_MESH_Tunnel * tunnel,
2277 const struct GNUNET_MessageHeader * message)
2279 struct ServiceSession * session;
2280 const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2281 unsigned char * current;
2284 uint32_t contained=0;
2288 GNUNET_assert (NULL != message);
2289 session = (struct ServiceSession *) * tunnel_ctx;
2290 // are we in the correct state?
2291 if (session->state != WAITING_FOR_SERVICE_REQUEST) {
2294 //we need at least a full message without elements attached
2295 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) + 2 * PAILLIER_ELEMENT_LENGTH > ntohs (msg->header.size)) {
2298 contained = ntohl (msg->contained_element_count);
2299 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2300 + 2 * contained * 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 < contained)) {
2306 session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2307 session->transferred = contained;
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);
2315 current += PAILLIER_ELEMENT_LENGTH;
2317 if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2318 PAILLIER_ELEMENT_LENGTH, &read))) {
2319 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2322 current += PAILLIER_ELEMENT_LENGTH;
2323 session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2324 session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2325 // Convert each k[][perm] to its MPI_value
2326 for (i = 0; i < contained; i++) {
2327 if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2328 PAILLIER_ELEMENT_LENGTH, &read))) {
2329 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2332 current += PAILLIER_ELEMENT_LENGTH;
2333 if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2334 PAILLIER_ELEMENT_LENGTH, &read))) {
2335 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2338 current += PAILLIER_ELEMENT_LENGTH;
2340 if (session->transferred != session->used)
2341 return GNUNET_OK; //wait for the other multipart chunks
2343 session->state = SERVICE_RESPONSE_RECEIVED;
2344 session->product = compute_scalar_product (session);
2345 return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2348 GNUNET_break_op (0);
2349 free_session_variables (session);
2350 session->state = FINALIZED;
2351 session->tunnel = NULL;
2352 // send message with product to client
2353 if (ALICE == session->role)
2354 session->client_notification_task =
2355 GNUNET_SCHEDULER_add_now (&prepare_client_response,
2357 // the tunnel has done its job, terminate our connection and the tunnel
2358 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2359 // just close the connection, as recommended by Christian
2360 return GNUNET_SYSERR;
2364 * Task run during shutdown.
2370 shutdown_task (void *cls,
2371 const struct GNUNET_SCHEDULER_TaskContext *tc)
2373 struct ServiceSession * session;
2374 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2376 do_shutdown = GNUNET_YES;
2378 // terminate all owned open tunnels.
2379 for (session = from_client_head; NULL != session; session = session->next) {
2380 if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2381 GNUNET_MESH_tunnel_destroy (session->tunnel);
2382 session->tunnel = NULL;
2384 if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2385 GNUNET_SCHEDULER_cancel (session->client_notification_task);
2386 session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2388 if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2389 GNUNET_SCHEDULER_cancel (session->service_request_task);
2390 session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2392 if (NULL != session->client) {
2393 GNUNET_SERVER_client_disconnect (session->client);
2394 session->client = NULL;
2397 for (session = from_service_head; NULL != session; session = session->next)
2398 if (NULL != session->tunnel) {
2399 GNUNET_MESH_tunnel_destroy (session->tunnel);
2400 session->tunnel = NULL;
2404 GNUNET_MESH_disconnect (my_mesh);
2410 * Initialization of the program and message handlers
2412 * @param cls closure
2413 * @param server the initialized server
2414 * @param c configuration to use
2418 struct GNUNET_SERVER_Handle *server,
2419 const struct GNUNET_CONFIGURATION_Handle *c)
2421 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2422 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2423 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2426 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2427 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2428 { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2429 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2430 { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2433 static const uint32_t ports[] = {
2434 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2437 //generate private/public key set
2438 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2440 // register server callbacks and disconnect handler
2441 GNUNET_SERVER_add_handlers (server, server_handlers);
2442 GNUNET_SERVER_disconnect_notify (server,
2443 &handle_client_disconnect,
2445 GNUNET_break (GNUNET_OK ==
2446 GNUNET_CRYPTO_get_peer_identity (c,
2448 my_mesh = GNUNET_MESH_connect (c, NULL,
2449 &tunnel_incoming_handler,
2450 &tunnel_destruction_handler,
2451 mesh_handlers, ports);
2453 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2454 GNUNET_SCHEDULER_shutdown ();
2457 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2458 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2464 * The main function for the scalarproduct service.
2466 * @param argc number of arguments from the command line
2467 * @param argv command line arguments
2468 * @return 0 ok, 1 on error
2471 main (int argc, char *const *argv)
2473 return (GNUNET_OK ==
2474 GNUNET_SERVICE_run (argc, argv,
2476 GNUNET_SERVICE_OPTION_NONE,
2477 &run, NULL)) ? 0 : 1;
2480 /* end of gnunet-service-ext.c */