made the service more resilient against out of order and simply incorrect messages
[oweals/gnunet.git] / src / scalarproduct / gnunet-service-scalarproduct.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19  */
20
21 /**
22  * @file scalarproduct/gnunet-service-scalarproduct.c
23  * @brief scalarproduct service implementation
24  * @author Christian M. Fuchs
25  */
26 #include <limits.h>
27 #include "platform.h"
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"
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
37
38 ///////////////////////////////////////////////////////////////////////////////
39 //                     Service Structure Definitions
40 ///////////////////////////////////////////////////////////////////////////////
41
42 /**
43  * state a session can be in
44  */
45 enum SessionState
46 {
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,
55  FINALIZED
56 };
57
58 /**
59  * role a peer in a session can assume
60  */
61 enum PeerRole
62 {
63  ALICE,
64  BOB
65 };
66
67 /**
68  * A scalarproduct session which tracks:
69  *
70  * a request form the client to our final response.
71  * or
72  * a request from a service to us(service).
73  */
74 struct ServiceSession
75 {
76  /**
77   * the role this peer has
78   */
79  enum PeerRole role;
80
81  /**
82   * session information is kept in a DLL
83   */
84  struct ServiceSession *next;
85
86  /**
87   * session information is kept in a DLL
88   */
89  struct ServiceSession *prev;
90
91  /**
92   * (hopefully) unique transaction ID
93   */
94  struct GNUNET_HashCode key;
95
96  /**
97   * state of the session
98   */
99  enum SessionState state;
100
101  /**
102   * Alice or Bob's peerID
103   */
104  struct GNUNET_PeerIdentity peer;
105
106  /**
107   * the client this request is related to
108   */
109  struct GNUNET_SERVER_Client * client;
110
111  /**
112   * The message to send
113   */
114  struct GNUNET_MessageHeader * msg;
115
116  /**
117   * how many elements we were supplied with from the client
118   */
119  uint32_t element_count;
120
121  /**
122   * how many elements actually are used after applying the mask
123   */
124  uint32_t used_element_count;
125
126  /**
127   * already transferred elements (sent/received) for multipart messages, less or equal than used_element_count for
128   */
129  uint32_t transferred_element_count;
130
131  /**
132   * index of the last transferred element for multipart messages
133   */
134  uint32_t last_processed_element;
135
136  /**
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
139   */
140  uint32_t mask_length;
141
142  /**
143   * all the vector elements we received
144   */
145  int32_t * vector;
146
147  /**
148   * mask of which elements to check
149   */
150  unsigned char * mask;
151
152  /**
153   * Public key of the remote service, only used by bob
154   */
155  gcry_sexp_t remote_pubkey;
156
157  /**
158   * E(ai)(Bob) or ai(Alice) after applying the mask
159   */
160  gcry_mpi_t * a;
161
162  /**
163   * Bob's permutation p of R
164   */
165  gcry_mpi_t * r;
166
167  /**
168   * Bob's permutation q of R
169   */
170  gcry_mpi_t * r_prime;
171  
172  /**
173   * Bob's s
174   */
175  gcry_mpi_t s;
176  
177  /**
178   * Bob's s'
179   */
180  gcry_mpi_t s_prime;
181
182  /**
183   * Bobs matching response session from the client
184   */
185  struct ServiceSession * response;
186
187  /**
188   * The computed scalar
189   */
190  gcry_mpi_t product;
191
192  /**
193   * My transmit handle for the current message to a alice/bob
194   */
195  struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
196
197  /**
198   * My transmit handle for the current message to the client
199   */
200  struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
201
202  /**
203   * tunnel-handle associated with our mesh handle
204   */
205  struct GNUNET_MESH_Tunnel * tunnel;
206
207  GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
208
209  GNUNET_SCHEDULER_TaskIdentifier service_request_task;
210 };
211
212 ///////////////////////////////////////////////////////////////////////////////
213 //                      Global Variables
214 ///////////////////////////////////////////////////////////////////////////////
215
216
217 /**
218  * Handle to the core service (NULL until we've connected to it).
219  */
220 static struct GNUNET_MESH_Handle *my_mesh;
221
222 /**
223  * The identity of this host.
224  */
225 static struct GNUNET_PeerIdentity me;
226
227 /**
228  * Service's own public key represented as string
229  */
230 static unsigned char * my_pubkey_external;
231
232 /**
233  * Service's own public key represented as string
234  */
235 static uint32_t my_pubkey_external_length = 0;
236
237 /**
238  * Service's own n
239  */
240 static gcry_mpi_t my_n;
241
242 /**
243  * Service's own n^2 (kept for performance)
244  */
245 static gcry_mpi_t my_nsquare;
246
247 /**
248  * Service's own public exponent
249  */
250 static gcry_mpi_t my_g;
251
252 /**
253  * Service's own private multiplier
254  */
255 static gcry_mpi_t my_mu;
256
257 /**
258  * Service's own private exponent
259  */
260 static gcry_mpi_t my_lambda;
261
262 /**
263  * Service's offset for values that could possibly be negative but are plaintext for encryption.
264  */
265 static gcry_mpi_t my_offset;
266
267 /**
268  * Head of our double linked list for client-requests sent to us.
269  * for all of these elements we calculate a scalar product with a remote peer
270  * split between service->service and client->service for simplicity
271  */
272 static struct ServiceSession * from_client_head;
273 /**
274  * Tail of our double linked list for client-requests sent to us.
275  * for all of these elements we calculate a scalar product with a remote peer
276  * split between service->service and client->service for simplicity
277  */
278 static struct ServiceSession * from_client_tail;
279
280 /**
281  * Head of our double linked list for service-requests sent to us.
282  * for all of these elements we help the requesting service in calculating a scalar product
283  * split between service->service and client->service for simplicity
284  */
285 static struct ServiceSession * from_service_head;
286
287 /**
288  * Tail of our double linked list for service-requests sent to us.
289  * for all of these elements we help the requesting service in calculating a scalar product
290  * split between service->service and client->service for simplicity
291  */
292 static struct ServiceSession * from_service_tail;
293
294 /**
295  * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
296  */
297 static int do_shutdown;
298
299 ///////////////////////////////////////////////////////////////////////////////
300 //                      Helper Functions
301 ///////////////////////////////////////////////////////////////////////////////
302
303 /**
304  * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
305  */
306 static void
307 generate_keyset ()
308 {
309   gcry_sexp_t gen_params;
310   gcry_sexp_t key;
311   gcry_sexp_t tmp_sexp;
312   gcry_mpi_t p;
313   gcry_mpi_t q;
314   gcry_mpi_t tmp1;
315   gcry_mpi_t tmp2;
316   gcry_mpi_t gcd;
317
318   size_t erroff = 0;
319
320   // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
321   GNUNET_assert (0 == gcry_sexp_build (&gen_params, &erroff,
322                                        "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
323                                        KEYBITS));
324
325   GNUNET_assert (0 == gcry_pk_genkey (&key, gen_params));
326   gcry_sexp_release (gen_params);
327
328   // get n and d of our publickey as MPI
329   tmp_sexp = gcry_sexp_find_token (key, "n", 0);
330   GNUNET_assert (tmp_sexp);
331   my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
332   gcry_sexp_release (tmp_sexp);
333   tmp_sexp = gcry_sexp_find_token (key, "p", 0);
334   GNUNET_assert (tmp_sexp);
335   p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
336   gcry_sexp_release (tmp_sexp);
337   tmp_sexp = gcry_sexp_find_token (key, "q", 0);
338   GNUNET_assert (tmp_sexp);
339   q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
340   gcry_sexp_release (key);
341
342   tmp1 = gcry_mpi_new (0);
343   tmp2 = gcry_mpi_new (0);
344   gcd = gcry_mpi_new (0);
345   my_g = gcry_mpi_new (0);
346   my_mu = gcry_mpi_new (0);
347   my_nsquare = gcry_mpi_new (0);
348   my_lambda = gcry_mpi_new (0);
349
350   // calculate lambda
351   // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
352   gcry_mpi_sub_ui (tmp1, p, 1);
353   gcry_mpi_sub_ui (tmp2, q, 1);
354   gcry_mpi_gcd (gcd, tmp1, tmp2);
355   gcry_mpi_set (my_lambda, tmp1);
356   gcry_mpi_mul (my_lambda, my_lambda, tmp2);
357   gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
358
359   // generate a g
360   gcry_mpi_mul (my_nsquare, my_n, my_n);
361   do {
362     // find a matching g
363     do {
364       gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
365       // g must be smaller than n^2
366       if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
367         continue;
368
369       // g must have gcd == 1 with n^2
370       gcry_mpi_gcd (gcd, my_g, my_nsquare);
371     }
372     while (gcry_mpi_cmp_ui (gcd, 1));
373
374     // is this a valid g?
375     // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
376     gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
377     gcry_mpi_sub_ui (tmp1, tmp1, 1);
378     gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
379     gcry_mpi_gcd (gcd, tmp1, my_n);
380   }
381   while (gcry_mpi_cmp_ui (gcd, 1));
382
383   // calculate our mu based on g and n.
384   // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
385   gcry_mpi_invm (my_mu, tmp1, my_n);
386
387   GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
388                                        "(public-key (paillier (n %M)(g %M)))",
389                                        my_n, my_g));
390
391   // get the length of this sexpression
392   my_pubkey_external_length = gcry_sexp_sprint (key,
393                                                 GCRYSEXP_FMT_CANON,
394                                                 NULL,
395                                                 UINT16_MAX);
396
397   GNUNET_assert (my_pubkey_external_length > 0);
398   my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
399
400   // convert the sexpression to canonical format
401   gcry_sexp_sprint (key,
402                     GCRYSEXP_FMT_CANON,
403                     my_pubkey_external,
404                     my_pubkey_external_length);
405
406   gcry_sexp_release (key);
407
408   // offset has to be sufficiently small to allow computation of:
409   // m1+m2 mod n == (S + a) + (S + b) mod n,
410   // if we have more complex operations, this factor needs to be lowered
411   my_offset = gcry_mpi_new (KEYBITS / 3);
412   gcry_mpi_set_bit (my_offset, KEYBITS / 3);
413
414   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
415 }
416
417 /**
418  * If target != size, move target bytes to the
419  * end of the size-sized buffer and zero out the
420  * first target-size bytes.
421  *
422  * @param buf original buffer
423  * @param size number of bytes in the buffer
424  * @param target target size of the buffer
425  */
426 static void
427 adjust (unsigned char *buf, size_t size, size_t target)
428 {
429   if (size < target) {
430     memmove (&buf[target - size], buf, size);
431     memset (buf, 0, target - size);
432   }
433 }
434
435 /**
436  * encrypts an element using the paillier crypto system
437  *
438  * @param c ciphertext (output)
439  * @param m plaintext
440  * @param g the public base
441  * @param n the module from which which r is chosen (Z*_n)
442  * @param n_square the module for encryption, for performance reasons.
443  */
444 static void
445 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
446 {
447   gcry_mpi_t tmp;
448
449   GNUNET_assert (tmp = gcry_mpi_new (0));
450
451   while (0 >= gcry_mpi_cmp_ui (tmp, 1)) {
452     gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
453     // r must be 1 < r < n
454   }
455
456   gcry_mpi_powm (c, g, m, n_square);
457   gcry_mpi_powm (tmp, tmp, n, n_square);
458   gcry_mpi_mulm (c, tmp, c, n_square);
459
460   gcry_mpi_release (tmp);
461 }
462
463 /**
464  * decrypts an element using the paillier crypto system
465  *
466  * @param m plaintext (output)
467  * @param c the ciphertext
468  * @param mu the modifier to correct encryption
469  * @param lambda the private exponent
470  * @param n the outer module for decryption
471  * @param n_square the inner module for decryption
472  */
473 static void
474 decrypt_element (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda, gcry_mpi_t n, gcry_mpi_t n_square)
475 {
476   gcry_mpi_powm (m, c, lambda, n_square);
477   gcry_mpi_sub_ui (m, m, 1);
478   gcry_mpi_div (m, NULL, m, n, 0);
479   gcry_mpi_mulm (m, m, mu, n);
480 }
481
482 /**
483  * computes the square sum over a vector of a given length.
484  *
485  * @param vector the vector to encrypt
486  * @param length the length of the vector
487  * @return an MPI value containing the calculated sum, never NULL
488  */
489 static gcry_mpi_t
490 compute_square_sum (gcry_mpi_t * vector, uint32_t length)
491 {
492   gcry_mpi_t elem;
493   gcry_mpi_t sum;
494   int32_t i;
495
496   GNUNET_assert (sum = gcry_mpi_new (0));
497   GNUNET_assert (elem = gcry_mpi_new (0));
498
499   // calculare E(sum (ai ^ 2), publickey)
500   for (i = 0; i < length; i++) {
501     gcry_mpi_mul (elem, vector[i], vector[i]);
502     gcry_mpi_add (sum, sum, elem);
503   }
504   gcry_mpi_release (elem);
505
506   return sum;
507 }
508
509
510 static void
511 prepare_service_request_multipart (void *cls,
512                                    const struct GNUNET_SCHEDULER_TaskContext *tc);
513 static void
514 prepare_service_response_multipart (void *cls,
515                                     const struct GNUNET_SCHEDULER_TaskContext *tc);
516
517 /**
518  * Primitive callback for copying over a message, as they
519  * usually are too complex to be handled in the callback itself.
520  * clears a session-callback, if a session was handed over and the transmit handle was stored
521  *
522  * @param cls the message object
523  * @param size the size of the buffer we got
524  * @param buf the buffer to copy the message to
525  * @return 0 if we couldn't copy, else the size copied over
526  */
527 static size_t
528 do_send_message (void *cls, size_t size, void *buf)
529 {
530   struct ServiceSession * session = cls;
531   size_t written = 0;
532
533   GNUNET_assert (buf);
534
535   if (ntohs (session->msg->size) == size) {
536     memcpy (buf, session->msg, size);
537     written = size;
538   }
539
540   switch (ntohs (session->msg->type))
541   {
542   case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
543     session->state = FINALIZED;
544     session->client_transmit_handle = NULL;
545     break;
546   case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB:
547   case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART:
548     //else
549     session->service_transmit_handle = NULL;
550     // reset flags for sending
551     if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
552       prepare_service_request_multipart (session, NULL);
553     //TODO we have sent a message and now need to trigger trigger the next multipart message sending
554     break;
555   case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE:
556   case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART:
557     //else
558     session->service_transmit_handle = NULL;
559     if ((session->state != WAITING_FOR_MULTIPART_TRANSMISSION) && (session->used_element_count != session->transferred_element_count))
560       prepare_service_response_multipart (session, NULL);
561     break;
562   default:
563     session->service_transmit_handle = NULL;
564   }
565
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Sent a message of type %hu.\n",
568               ntohs (session->msg->type));
569   GNUNET_free (session->msg);
570   session->msg = NULL;
571
572   return written;
573 }
574
575 /**
576  * initializes a new vector with fresh MPI values (=0) of a given length
577  *
578  * @param length of the vector to create
579  * @return the initialized vector, never NULL
580  */
581 static gcry_mpi_t *
582 initialize_mpi_vector (uint32_t length)
583 {
584   uint32_t i;
585   gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
586
587   for (i = 0; i < length; i++)
588     GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
589   return output;
590 }
591
592 /**
593  * permutes an MPI vector according to the given permutation vector
594  *
595  * @param vector the vector to permuted
596  * @param perm the permutation to use
597  * @param length the length of the vectors
598  * @return the permuted vector (same as input), never NULL
599  */
600 static gcry_mpi_t *
601 permute_vector (gcry_mpi_t * vector,
602                 unsigned int * perm,
603                 uint32_t length)
604 {
605   gcry_mpi_t tmp[length];
606   uint32_t i;
607
608   GNUNET_assert (length > 0);
609
610   // backup old layout
611   memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
612
613   // permute vector according to given
614   for (i = 0; i < length; i++)
615     vector[i] = tmp[perm[i]];
616
617   return vector;
618 }
619
620 /**
621  * Populate a vector with random integer values and convert them to
622  *
623  * @param length the length of the vector we must generate
624  * @return an array of MPI values with random values
625  */
626 static gcry_mpi_t *
627 generate_random_vector (uint32_t length)
628 {
629   gcry_mpi_t * random_vector;
630   int32_t value;
631   uint32_t i;
632
633   random_vector = initialize_mpi_vector (length);
634   for (i = 0; i < length; i++) {
635     value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
636
637     // long to gcry_mpi_t
638     if (value < 0)
639       gcry_mpi_sub_ui (random_vector[i],
640                        random_vector[i],
641                        -value);
642     else
643       random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
644   }
645
646   return random_vector;
647 }
648
649 /**
650  * Finds a not terminated client/service session in the
651  * given DLL based on session key, element count and state.
652  *
653  * @param tail - the tail of the DLL
654  * @param my - the session to compare it to
655  * @return a pointer to a matching session,
656  *         else NULL
657  */
658 static struct ServiceSession *
659 find_matching_session (struct ServiceSession * tail,
660                        const struct GNUNET_HashCode * key,
661                        uint32_t element_count,
662                        enum SessionState * state,
663                        const struct GNUNET_PeerIdentity * peerid)
664 {
665   struct ServiceSession * curr;
666
667   for (curr = tail; NULL != curr; curr = curr->prev) {
668     // if the key matches, and the element_count is same
669     if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
670         && (curr->element_count == element_count)) {
671       // if incoming state is NULL OR is same as state of the queued request
672       if ((NULL == state) || (curr->state == *state)) {
673         // if peerid is NULL OR same as the peer Id in the queued request
674         if ((NULL == peerid)
675             || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
676           // matches and is not an already terminated session
677           return curr;
678       }
679     }
680   }
681
682   return NULL;
683 }
684
685 static void
686 free_session (struct ServiceSession * session)
687 {
688   unsigned int i;
689
690   if (session->a) {
691     for (i = 0; i < session->used_element_count; i++)
692       gcry_mpi_release (session->a[i]);
693
694     GNUNET_free (session->a);
695   }
696   if (session->product)
697     gcry_mpi_release (session->product);
698
699   if (session->remote_pubkey)
700     gcry_sexp_release (session->remote_pubkey);
701
702   GNUNET_free_non_null (session->vector);
703   GNUNET_free (session);
704 }
705 ///////////////////////////////////////////////////////////////////////////////
706 //                      Event and Message Handlers
707 ///////////////////////////////////////////////////////////////////////////////
708
709 /**
710  * A client disconnected.
711  *
712  * Remove the associated session(s), release datastructures
713  * and cancel pending outgoing transmissions to the client.
714  * if the session has not yet completed, we also cancel Alice's request to Bob.
715  *
716  * @param cls closure, NULL
717  * @param client identification of the client
718  */
719 static void
720 handle_client_disconnect (void *cls,
721                           struct GNUNET_SERVER_Client *client)
722 {
723   struct ServiceSession *session;
724
725   if (client == NULL)
726     return;
727   session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
728   if (NULL == session)
729     return;
730   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
731               _ ("Client (%p) disconnected from us.\n"), client);
732   GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
733
734   if (!(session->role == BOB && session->state == FINALIZED)) {
735     //we MUST terminate any client message underway
736     if (session->service_transmit_handle && session->tunnel)
737       GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
738     if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
739       GNUNET_MESH_tunnel_destroy (session->tunnel);
740   }
741   if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
742     GNUNET_SCHEDULER_cancel (session->client_notification_task);
743     session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
744   }
745   if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
746     GNUNET_SCHEDULER_cancel (session->service_request_task);
747     session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
748   }
749   if (NULL != session->client_transmit_handle) {
750     GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
751     session->client_transmit_handle = NULL;
752   }
753   free_session (session);
754 }
755
756 /**
757  * Notify the client that the session has succeeded or failed completely.
758  * This message gets sent to
759  * * alice's client if bob disconnected or to
760  * * bob's client if the operation completed or alice disconnected
761  *
762  * @param client_session the associated client session
763  * @return GNUNET_NO, if we could not notify the client
764  *         GNUNET_YES if we notified it.
765  */
766 static void
767 prepare_client_end_notification (void * cls,
768                                  const struct GNUNET_SCHEDULER_TaskContext * tc)
769 {
770   struct ServiceSession * session = cls;
771   struct GNUNET_SCALARPRODUCT_client_response * msg;
772
773   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
774
775   msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
776   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
777   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
778   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
779   msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
780   // signal error if not signalized, positive result-range field but zero length.
781   msg->product_length = htonl (0);
782   msg->range = (session->state == FINALIZED) ? 0 : -1;
783
784   session->msg = &msg->header;
785
786   //transmit this message to our client
787   session->client_transmit_handle =
788           GNUNET_SERVER_notify_transmit_ready (session->client,
789                                                sizeof (struct GNUNET_SCALARPRODUCT_client_response),
790                                                GNUNET_TIME_UNIT_FOREVER_REL,
791                                                &do_send_message,
792                                                session);
793
794   // if we could not even queue our request, something is wrong
795   if (NULL == session->client_transmit_handle) {
796     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
797     // usually gets freed by do_send_message
798     session->msg = NULL;
799     GNUNET_free (msg);
800   }
801   else
802     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
803
804 }
805
806 static void
807 prepare_service_response_multipart (void *cls,
808                                     const struct GNUNET_SCHEDULER_TaskContext *tc)
809 {
810   struct ServiceSession * session = cls;
811   unsigned char * current;
812   unsigned char * element_exported;
813   struct GNUNET_SCALARPRODUCT_multipart_message * msg;
814   unsigned int i;
815   uint32_t msg_length;
816   uint32_t todo_count;
817   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
818
819   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
820   todo_count = session->used_element_count - session->transferred_element_count;
821
822   if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
823     // send the currently possible maximum chunk, we always transfer both permutations
824     todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
825
826   msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
827   msg = GNUNET_malloc (msg_length);
828   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
829   msg->header.size = htons (msg_length);
830   msg->multipart_element_count = htonl (todo_count);
831
832   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
833   current = (unsigned char *) &msg[1];
834   // convert k[][]
835   for (i = session->transferred_element_count; i < session->transferred_element_count + todo_count; i++) {
836     //k[i][p]
837     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
838     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
839                                         element_exported, PAILLIER_ELEMENT_LENGTH,
840                                         &element_length,
841                                         session->r[i]));
842     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
843     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
844     current += PAILLIER_ELEMENT_LENGTH;
845     //k[i][q]
846     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
847     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
848                                         element_exported, PAILLIER_ELEMENT_LENGTH,
849                                         &element_length,
850                                         session->r_prime[i]));
851     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
852     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
853     current += PAILLIER_ELEMENT_LENGTH;
854   }
855   GNUNET_free (element_exported);
856   for (i = session->transferred_element_count; i < session->transferred_element_count; i++) {
857     gcry_mpi_release (session->r_prime[i]);
858     gcry_mpi_release (session->r[i]);
859   }
860   session->transferred_element_count += todo_count;
861   session->msg = (struct GNUNET_MessageHeader *) msg;
862   session->service_transmit_handle =
863           GNUNET_MESH_notify_transmit_ready (session->tunnel,
864                                              GNUNET_YES,
865                                              GNUNET_TIME_UNIT_FOREVER_REL,
866                                              msg_length,
867                                              &do_send_message,
868                                              session);
869   //disconnect our client
870   if (NULL == session->service_transmit_handle) {
871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
872     session->state = FINALIZED;
873
874     session->response->client_notification_task =
875             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
876                                       session->response);
877     return;
878   }
879   if (session->transferred_element_count != session->used_element_count)
880     // multipart
881     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
882   else
883     //singlepart
884     session->state = FINALIZED;
885 }
886
887 /**
888  * Bob executes:
889  * generates the response message to be sent to alice after computing
890  * the values (1), (2), S and S'
891  *  (1)[]: $E_A(a_{pi(i)}) times E_A(- r_{pi(i)} - b_{pi(i)}) &= E_A(a_{pi(i)} - r_{pi(i)} - b_{pi(i)})$
892  *  (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
893  *      S: $S := E_A(sum (r_i + b_i)^2)$
894  *     S': $S' := E_A(sum r_i^2)$
895  *
896  * @param s         S: $S := E_A(sum (r_i + b_i)^2)$
897  * @param s_prime    S': $S' := E_A(sum r_i^2)$
898  * @param session  the associated requesting session with alice
899  * @return GNUNET_NO if we could not send our message
900  *         GNUNET_OK if the operation succeeded
901  */
902 static int
903 prepare_service_response (gcry_mpi_t s,
904                           gcry_mpi_t s_prime,
905                           struct ServiceSession * session)
906 {
907   struct GNUNET_SCALARPRODUCT_service_response * msg;
908   uint32_t msg_length = 0;
909   unsigned char * current = NULL;
910   unsigned char * element_exported = NULL;
911   size_t element_length = 0;
912   int i;
913
914   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
915           + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
916
917   if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH) { //kp, kq
918     msg_length += +2 * session->used_element_count * PAILLIER_ELEMENT_LENGTH;
919     session->transferred_element_count = session->used_element_count;
920   }
921   else {
922     session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
923   }
924
925   msg = GNUNET_malloc (msg_length);
926
927   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
928   msg->header.size = htons (msg_length);
929   msg->total_element_count = htonl (session->element_count);
930   msg->contained_element_count = htonl (session->used_element_count);
931   msg->contained_element_count = htonl (session->transferred_element_count);
932   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
933   current = (unsigned char *) &msg[1];
934
935   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
936   // 4 times the same logics with slight variations.
937   // doesn't really justify having 2 functions for that
938   // so i put it into blocks to enhance readability
939   // convert s
940   memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
941   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
942                                       element_exported, PAILLIER_ELEMENT_LENGTH,
943                                       &element_length,
944                                       s));
945   adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
946   memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
947   current += PAILLIER_ELEMENT_LENGTH;
948
949   // convert stick
950   memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
951   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
952                                       element_exported, PAILLIER_ELEMENT_LENGTH,
953                                       &element_length,
954                                       s_prime));
955   adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
956   memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
957   current += PAILLIER_ELEMENT_LENGTH;
958
959   // convert k[][]
960   for (i = 0; i < session->transferred_element_count; i++) {
961     //k[i][p]
962     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
963     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
964                                         element_exported, PAILLIER_ELEMENT_LENGTH,
965                                         &element_length,
966                                         session->r[i]));
967     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
968     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
969     current += PAILLIER_ELEMENT_LENGTH;
970     //k[i][q]
971     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
972     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
973                                         element_exported, PAILLIER_ELEMENT_LENGTH,
974                                         &element_length,
975                                         session->r_prime[i]));
976     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
977     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
978     current += PAILLIER_ELEMENT_LENGTH;
979   }
980
981   GNUNET_free (element_exported);
982   for (i = 0; i < session->transferred_element_count; i++) {
983     gcry_mpi_release (session->r_prime[i]);
984     gcry_mpi_release (session->r[i]);
985   }
986   gcry_mpi_release (s);
987   gcry_mpi_release (s_prime);
988
989   session->msg = (struct GNUNET_MessageHeader *) msg;
990   session->service_transmit_handle =
991           GNUNET_MESH_notify_transmit_ready (session->tunnel,
992                                              GNUNET_YES,
993                                              GNUNET_TIME_UNIT_FOREVER_REL,
994                                              msg_length,
995                                              &do_send_message,
996                                              session);
997   //disconnect our client
998   if (NULL == session->service_transmit_handle) {
999     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1000     session->state = FINALIZED;
1001
1002     session->response->client_notification_task =
1003             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1004                                       session->response);
1005     return GNUNET_NO;
1006   }
1007   if (session->transferred_element_count != session->used_element_count)
1008     // multipart
1009     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1010   else
1011     //singlepart
1012     session->state = FINALIZED;
1013
1014   return GNUNET_OK;
1015 }
1016
1017 /**
1018  * executed by bob:
1019  * compute the values
1020  *  (1)[]: $E_A(a_{\pi(i)}) \otimes E_A(- r_{\pi(i)} - b_{\pi(i)}) &= E_A(a_{\pi(i)} - r_{\pi(i)} - b_{\pi(i)})$
1021  *  (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1022  *      S: $S := E_A(\sum (r_i + b_i)^2)$
1023  *     S': $S' := E_A(\sum r_i^2)$
1024  *
1025  * @param request the requesting session + bob's requesting peer
1026  * @param response the responding session + bob's client handle
1027  * @return GNUNET_SYSERR if the computation failed
1028  *         GNUNET_OK if everything went well.
1029  */
1030 static int
1031 compute_service_response (struct ServiceSession * request,
1032                           struct ServiceSession * response)
1033 {
1034   int i;
1035   int j;
1036   int ret = GNUNET_SYSERR;
1037   unsigned int * p;
1038   unsigned int * q;
1039   uint32_t count;
1040   gcry_mpi_t * rand = NULL;
1041   gcry_mpi_t * r = NULL;
1042   gcry_mpi_t * r_prime = NULL;
1043   gcry_mpi_t * b;
1044   gcry_mpi_t * a_pi;
1045   gcry_mpi_t * a_pi_prime;
1046   gcry_mpi_t * b_pi;
1047   gcry_mpi_t * rand_pi;
1048   gcry_mpi_t * rand_pi_prime;
1049   gcry_mpi_t s = NULL;
1050   gcry_mpi_t s_prime = NULL;
1051   gcry_mpi_t remote_n = NULL;
1052   gcry_mpi_t remote_nsquare;
1053   gcry_mpi_t remote_g = NULL;
1054   gcry_sexp_t tmp_exp;
1055   uint32_t value;
1056
1057   count = request->used_element_count;
1058
1059   b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1060   a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1061   b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1062   a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1063   rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1064   rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1065
1066   // convert responder session to from long to mpi
1067   for (i = 0, j = 0; i < response->element_count && j < count; i++) {
1068     if (request->mask[i / 8] & (1 << (i % 8))) {
1069       value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1070       // long to gcry_mpi_t
1071       if (0 > response->vector[i]) {
1072         b[j] = gcry_mpi_new (0);
1073         gcry_mpi_sub_ui (b[j], b[j], value);
1074       }
1075       else {
1076         b[j] = gcry_mpi_set_ui (NULL, value);
1077       }
1078       j++;
1079     }
1080   }
1081   GNUNET_free (response->vector);
1082   response->vector = NULL;
1083
1084   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1085   if (!tmp_exp) {
1086     GNUNET_break_op (0);
1087     gcry_sexp_release (request->remote_pubkey);
1088     request->remote_pubkey = NULL;
1089     goto except;
1090   }
1091   remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1092   if (!remote_n) {
1093     GNUNET_break (0);
1094     gcry_sexp_release (tmp_exp);
1095     goto except;
1096   }
1097   remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1098   gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1099   gcry_sexp_release (tmp_exp);
1100   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1101   gcry_sexp_release (request->remote_pubkey);
1102   request->remote_pubkey = NULL;
1103   if (!tmp_exp) {
1104     GNUNET_break_op (0);
1105     gcry_mpi_release (remote_n);
1106     goto except;
1107   }
1108   remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1109   if (!remote_g) {
1110     GNUNET_break (0);
1111     gcry_mpi_release (remote_n);
1112     gcry_sexp_release (tmp_exp);
1113     goto except;
1114   }
1115   gcry_sexp_release (tmp_exp);
1116
1117   // generate r, p and q
1118   rand = generate_random_vector (count);
1119   p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1120   q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1121   //initialize the result vectors
1122   r = initialize_mpi_vector (count);
1123   r_prime = initialize_mpi_vector (count);
1124
1125   // copy the REFERNCES of a, b and r into aq and bq. we will not change
1126   // those values, thus we can work with the references
1127   memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1128   memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1129   memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1130   memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1131   memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1132
1133   // generate p and q permutations for a, b and r
1134   GNUNET_assert (permute_vector (a_pi, p, count));
1135   GNUNET_assert (permute_vector (b_pi, p, count));
1136   GNUNET_assert (permute_vector (rand_pi, p, count));
1137   GNUNET_assert (permute_vector (a_pi_prime, q, count));
1138   GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1139
1140   // encrypt the element
1141   // for the sake of readability I decided to have dedicated permutation
1142   // vectors, which get rid of all the lookups in p/q.
1143   // however, ap/aq are not absolutely necessary but are just abstraction
1144   // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1145   for (i = 0; i < count; i++) {
1146     // E(S - r_pi - b_pi)
1147     gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1148     gcry_mpi_sub (r[i], r[i], b_pi[i]);
1149     encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1150
1151     // E(S - r_pi - b_pi) * E(S + a_pi) ==  E(2*S + a - r - b)
1152     gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1153   }
1154   GNUNET_free (a_pi);
1155   GNUNET_free (b_pi);
1156   GNUNET_free (rand_pi);
1157
1158   // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1159   for (i = 0; i < count; i++) {
1160     // E(S - r_qi)
1161     gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1162     encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1163
1164     // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1165     gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1166   }
1167   GNUNET_free (a_pi_prime);
1168   GNUNET_free (rand_pi_prime);
1169
1170   request->r = r;
1171   request->r_prime = r_prime;
1172   request->response = response;
1173
1174   // Calculate S' =  E(SUM( r_i^2 ))
1175   s_prime = compute_square_sum (rand, count);
1176   encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1177
1178   // Calculate S = E(SUM( (r_i + b_i)^2 ))
1179   for (i = 0; i < count; i++) {
1180     gcry_mpi_add (rand[i], rand[i], b[i]);
1181   }
1182   s = compute_square_sum (rand, count);
1183   encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1184   gcry_mpi_release (remote_n);
1185   gcry_mpi_release (remote_g);
1186   gcry_mpi_release (remote_nsquare);
1187
1188   // release r and tmp
1189   for (i = 0; i < count; i++)
1190     // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1191     gcry_mpi_release (rand[i]);
1192
1193   // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1194   if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1195     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1196                 GNUNET_i2s (&request->peer));
1197   else
1198     ret = GNUNET_OK;
1199
1200 except:
1201   for (i = 0; i < count; i++) {
1202     gcry_mpi_release (b[i]);
1203     gcry_mpi_release (request->a[i]);
1204   }
1205
1206   GNUNET_free (b);
1207   GNUNET_free (request->a);
1208   request->a = NULL;
1209
1210   return ret;
1211 }
1212
1213 static void
1214 prepare_service_request_multipart (void *cls,
1215                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1216 {
1217   struct ServiceSession * session = cls;
1218   unsigned char * current;
1219   unsigned char * element_exported;
1220   struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1221   unsigned int i;
1222   unsigned int j;
1223   uint32_t msg_length;
1224   uint32_t todo_count;
1225   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1226   gcry_mpi_t a;
1227   uint32_t value;
1228
1229   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1230   todo_count = session->used_element_count - session->transferred_element_count;
1231
1232   if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1233     // send the currently possible maximum chunk
1234     todo_count = MULTIPART_ELEMENT_CAPACITY;
1235
1236   msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1237   msg = GNUNET_malloc (msg_length);
1238   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1239   msg->header.size = htons (msg_length);
1240   msg->multipart_element_count = htonl (todo_count);
1241
1242   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1243   a = gcry_mpi_new (KEYBITS * 2);
1244   current = (unsigned char *) &msg[1];
1245   // encrypt our vector and generate string representations
1246   for (i = session->last_processed_element, j = 0; i < session->element_count; i++) {
1247     // is this a used element?
1248     if (session->mask[i / 8] & 1 << (i % 8)) {
1249       if (todo_count <= j)
1250         break; //reached end of this message, can't include more
1251
1252       memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1253       value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1254
1255       a = gcry_mpi_set_ui (a, 0);
1256       // long to gcry_mpi_t
1257       if (session->vector[i] < 0)
1258         gcry_mpi_sub_ui (a, a, value);
1259       else
1260         gcry_mpi_add_ui (a, a, value);
1261
1262       session->a[session->transferred_element_count + j++] = gcry_mpi_set (NULL, a);
1263       gcry_mpi_add (a, a, my_offset);
1264       encrypt_element (a, a, my_g, my_n, my_nsquare);
1265
1266       // get representation as string
1267       // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1268       GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1269                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1270                                       &element_length,
1271                                       a));
1272
1273       // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1274       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1275
1276       // copy over to the message
1277       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1278       current += PAILLIER_ELEMENT_LENGTH;
1279     }
1280   }
1281   gcry_mpi_release (a);
1282   GNUNET_free (element_exported);
1283   session->transferred_element_count += todo_count;
1284
1285   session->msg = (struct GNUNET_MessageHeader *) msg;
1286   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1287
1288   //transmit via mesh messaging
1289   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1290                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1291                                                                         msg_length,
1292                                                                         &do_send_message,
1293                                                                         session);
1294   if (!session->service_transmit_handle) {
1295     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1296     GNUNET_free (msg);
1297     session->msg = NULL;
1298     session->client_notification_task =
1299             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1300                                       session);
1301     return;
1302   }
1303   if (session->transferred_element_count != session->used_element_count) {
1304     session->last_processed_element = i;
1305   }
1306   else
1307     //final part
1308     session->state = WAITING_FOR_SERVICE_RESPONSE;
1309 }
1310
1311 /**
1312  * Executed by Alice, fills in a service-request message and sends it to the given peer
1313  *
1314  * @param session the session associated with this request, then also holds the CORE-handle
1315  * @return #GNUNET_SYSERR if we could not send the message
1316  *         #GNUNET_NO if the message was too large
1317  *         #GNUNET_OK if we sent it
1318  */
1319 static void
1320 prepare_service_request (void *cls,
1321                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1322 {
1323   struct ServiceSession * session = cls;
1324   unsigned char * current;
1325   unsigned char * element_exported;
1326   struct GNUNET_SCALARPRODUCT_service_request * msg;
1327   unsigned int i;
1328   unsigned int j;
1329   uint32_t msg_length;
1330   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1331   gcry_mpi_t a;
1332   uint32_t value;
1333
1334   session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1335
1336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1337
1338   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1339           +session->mask_length
1340           + my_pubkey_external_length;
1341
1342   if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used_element_count * PAILLIER_ELEMENT_LENGTH) {
1343     msg_length += session->used_element_count * PAILLIER_ELEMENT_LENGTH;
1344     session->transferred_element_count = session->used_element_count;
1345   }
1346   else {
1347     //create a multipart msg, first we calculate a new msg size for the head msg
1348     session->transferred_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1349   }
1350
1351   msg = GNUNET_malloc (msg_length);
1352   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1353   msg->total_element_count = htonl (session->used_element_count);
1354   msg->contained_element_count = htonl (session->transferred_element_count);
1355   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1356   msg->mask_length = htonl (session->mask_length);
1357   msg->pk_length = htonl (my_pubkey_external_length);
1358   msg->element_count = htonl (session->element_count);
1359   msg->header.size = htons (msg_length);
1360
1361   // fill in the payload
1362   current = (unsigned char *) &msg[1];
1363   // copy over the mask
1364   memcpy (current, session->mask, session->mask_length);
1365   // copy over our public key
1366   current += session->mask_length;
1367   memcpy (current, my_pubkey_external, my_pubkey_external_length);
1368   current += my_pubkey_external_length;
1369
1370   // now copy over the element vector
1371   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1372   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1373   a = gcry_mpi_new (KEYBITS * 2);
1374   // encrypt our vector and generate string representations
1375   for (i = 0, j = 0; i < session->element_count; i++) {
1376     // if this is a used element...
1377     if (session->mask[i / 8] & 1 << (i % 8)) {
1378       if (session->transferred_element_count <= j)
1379         break; //reached end of this message, can't include more
1380
1381       memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1382       value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1383
1384       a = gcry_mpi_set_ui (a, 0);
1385       // long to gcry_mpi_t
1386       if (session->vector[i] < 0)
1387         gcry_mpi_sub_ui (a, a, value);
1388       else
1389         gcry_mpi_add_ui (a, a, value);
1390
1391       session->a[j++] = gcry_mpi_set (NULL, a);
1392       gcry_mpi_add (a, a, my_offset);
1393       encrypt_element (a, a, my_g, my_n, my_nsquare);
1394
1395       // get representation as string
1396       // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1397       GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1398                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1399                                       &element_length,
1400                                       a));
1401
1402       // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1403       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1404
1405       // copy over to the message
1406       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1407       current += PAILLIER_ELEMENT_LENGTH;
1408     }
1409   }
1410   gcry_mpi_release (a);
1411   GNUNET_free (element_exported);
1412
1413   session->msg = (struct GNUNET_MessageHeader *) msg;
1414   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1415
1416   //transmit via mesh messaging
1417   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1418                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1419                                                                         msg_length,
1420                                                                         &do_send_message,
1421                                                                         session);
1422   if (!session->service_transmit_handle) {
1423     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1424     GNUNET_free (msg);
1425     session->msg = NULL;
1426     session->client_notification_task =
1427             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1428                                       session);
1429     return;
1430   }
1431   if (session->transferred_element_count != session->used_element_count) {
1432     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1433     session->last_processed_element = i;
1434   }
1435   else
1436     //singlepart message
1437     session->state = WAITING_FOR_SERVICE_RESPONSE;
1438 }
1439
1440 /**
1441  * Handler for a client request message.
1442  * Can either be type A or B
1443  *   A: request-initiation to compute a scalar product with a peer
1444  *   B: response role, keep the values + session and wait for a matching session or process a waiting request
1445  *
1446  * @param cls closure
1447  * @param client identification of the client
1448  * @param message the actual message
1449  */
1450 static void
1451 handle_client_request (void *cls,
1452                        struct GNUNET_SERVER_Client *client,
1453                        const struct GNUNET_MessageHeader *message)
1454 {
1455   const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1456   struct ServiceSession * session;
1457   uint32_t element_count;
1458   uint32_t mask_length;
1459   uint32_t msg_type;
1460   int32_t * vector;
1461   uint32_t i;
1462
1463   // only one concurrent session per client connection allowed, simplifies logics a lot...
1464   session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1465   if ((NULL != session) && (session->state != FINALIZED)) {
1466     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1467     return;
1468   }
1469   else if (NULL != session) {
1470     // old session is already completed, clean it up
1471     GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1472     free_session (session);
1473   }
1474
1475   //we need at least a peer and one message id to compare
1476   if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1477     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1478                 _ ("Too short message received from client!\n"));
1479     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1480     return;
1481   }
1482
1483   msg_type = ntohs (msg->header.type);
1484   element_count = ntohl (msg->element_count);
1485   mask_length = ntohl (msg->mask_length);
1486
1487   //sanity check: is the message as long as the message_count fields suggests?
1488   if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1489       || (0 == element_count)) {
1490     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1491                 _ ("Invalid message received from client, session information incorrect!\n"));
1492     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1493     return;
1494   }
1495
1496   // do we have a duplicate session here already?
1497   if (NULL != find_matching_session (from_client_tail,
1498                                      &msg->key,
1499                                      element_count,
1500                                      NULL, NULL)) {
1501     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1502                 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1503                 GNUNET_h2s (&msg->key));
1504     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1505     return;
1506   }
1507
1508   session = GNUNET_new (struct ServiceSession);
1509   session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1510   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1511   session->client = client;
1512   session->element_count = element_count;
1513   session->mask_length = mask_length;
1514   // get our transaction key
1515   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1516   //allocate memory for vector and encrypted vector
1517   session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1518   vector = (int32_t *) & msg[1];
1519
1520   if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1521     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1522                 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1523                 GNUNET_h2s (&session->key));
1524
1525     session->role = ALICE;
1526     // fill in the mask
1527     session->mask = GNUNET_malloc (mask_length);
1528     memcpy (session->mask, &vector[element_count], mask_length);
1529
1530     // copy over the elements
1531     session->used_element_count = 0;
1532     for (i = 0; i < element_count; i++) {
1533       session->vector[i] = ntohl (vector[i]);
1534       if (session->vector[i] == 0)
1535         session->mask[i / 8] &= ~(1 << (i % 8));
1536       if (session->mask[i / 8] & (1 << (i % 8)))
1537         session->used_element_count++;
1538     }
1539
1540     if (0 == session->used_element_count) {
1541       GNUNET_break_op (0);
1542       GNUNET_free (session->vector);
1543       GNUNET_free (session);
1544       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1545       return;
1546     }
1547     //session with ourself makes no sense!
1548     if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1549       GNUNET_break (0);
1550       GNUNET_free (session->vector);
1551       GNUNET_free (session);
1552       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1553       return;
1554     }
1555     // get our peer ID
1556     memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1557     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1558                 _ ("Creating new tunnel to for session with key %s.\n"),
1559                 GNUNET_h2s (&session->key));
1560     session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1561                                                  &session->peer,
1562                                                  GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1563                                                  GNUNET_NO,
1564                                                  GNUNET_YES);
1565     //prepare_service_request, tunnel_peer_disconnect_handler,
1566     if (!session->tunnel) {
1567       GNUNET_break (0);
1568       GNUNET_free (session->vector);
1569       GNUNET_free (session);
1570       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1571       return;
1572     }
1573     GNUNET_SERVER_client_set_user_context (client, session);
1574     GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1575
1576     session->state = CLIENT_REQUEST_RECEIVED;
1577     session->service_request_task =
1578             GNUNET_SCHEDULER_add_now (&prepare_service_request,
1579                                       session);
1580
1581   }
1582   else {
1583     struct ServiceSession * requesting_session;
1584     enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1585
1586     session->role = BOB;
1587     session->mask = NULL;
1588     // copy over the elements
1589     session->used_element_count = element_count;
1590     for (i = 0; i < element_count; i++)
1591       session->vector[i] = ntohl (vector[i]);
1592     session->state = CLIENT_RESPONSE_RECEIVED;
1593
1594     GNUNET_SERVER_client_set_user_context (client, session);
1595     GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1596
1597     //check if service queue contains a matching request
1598     requesting_session = find_matching_session (from_service_tail,
1599                                                 &session->key,
1600                                                 session->element_count,
1601                                                 &needed_state, NULL);
1602     if (NULL != requesting_session) {
1603       GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s and a matching service-request-session set, processing.\n"), GNUNET_h2s (&session->key));
1604       if (GNUNET_OK != compute_service_response (requesting_session, session))
1605         session->client_notification_task =
1606               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1607                                         session);
1608
1609     }
1610     else {
1611       GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s but NO matching service-request-session set, queuing element for later use.\n"), GNUNET_h2s (&session->key));
1612       // no matching session exists yet, store the response
1613       // for later processing by handle_service_request()
1614     }
1615   }
1616   GNUNET_SERVER_receive_done (client, GNUNET_YES);
1617 }
1618
1619 /**
1620  * Function called for inbound tunnels.
1621  *
1622  * @param cls closure
1623  * @param tunnel new handle to the tunnel
1624  * @param initiator peer that started the tunnel
1625  * @param atsi performance information for the tunnel
1626  * @return initial tunnel context for the tunnel
1627  *         (can be NULL -- that's not an error)
1628  */
1629 static void *
1630 tunnel_incoming_handler (void *cls,
1631                          struct GNUNET_MESH_Tunnel *tunnel,
1632                          const struct GNUNET_PeerIdentity *initiator,
1633                          uint32_t port)
1634 {
1635   struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1636
1637   c->peer = *initiator;
1638   c->tunnel = tunnel;
1639   c->role = BOB;
1640   c->state = WAITING_FOR_SERVICE_REQUEST;
1641   return c;
1642 }
1643
1644 /**
1645  * Function called whenever a tunnel is destroyed.  Should clean up
1646  * any associated state.
1647  *
1648  * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1649  *
1650  * @param cls closure (set from GNUNET_MESH_connect)
1651  * @param tunnel connection to the other end (henceforth invalid)
1652  * @param tunnel_ctx place where local state associated
1653  *                   with the tunnel is stored
1654  */
1655 static void
1656 tunnel_destruction_handler (void *cls,
1657                             const struct GNUNET_MESH_Tunnel *tunnel,
1658                             void *tunnel_ctx)
1659 {
1660   struct ServiceSession * session = tunnel_ctx;
1661   struct ServiceSession * client_session;
1662   struct ServiceSession * curr;
1663
1664   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665               _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1666               GNUNET_h2s (&session->key),
1667               GNUNET_i2s (&session->peer));
1668   if (ALICE == session->role) {
1669     // as we have only one peer connected in each session, just remove the session
1670
1671     if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1672       session->tunnel = NULL;
1673       // if this happened before we received the answer, we must terminate the session
1674       session->client_notification_task =
1675               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1676                                         session);
1677     }
1678   }
1679   else { //(BOB == session->role) service session
1680     // remove the session, unless it has already been dequeued, but somehow still active
1681     // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1682     // scenario: disconnect before alice can send her message to bob.
1683     for (curr = from_service_head; NULL != curr; curr = curr->next)
1684       if (curr == session) {
1685         GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1686         break;
1687       }
1688     // there is a client waiting for this service session, terminate it, too!
1689     // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1690     client_session = find_matching_session (from_client_tail,
1691                                             &session->key,
1692                                             session->element_count,
1693                                             NULL, NULL);
1694     free_session (session);
1695
1696     // the client has to check if it was waiting for a result
1697     // or if it was a responder, no point in adding more statefulness
1698     if (client_session && (!do_shutdown)) {
1699       client_session->state = FINALIZED;
1700       client_session->client_notification_task =
1701               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1702                                         client_session);
1703     }
1704   }
1705 }
1706
1707 /**
1708  * Compute our scalar product, done by Alice
1709  *
1710  * @param session - the session associated with this computation
1711  * @param kp - (1) from the protocol definition:
1712  *             $E_A(a_{\pi(i)}) \otimes E_A(- r_{\pi(i)} - b_{\pi(i)}) &= E_A(a_{\pi(i)} - r_{\pi(i)} - b_{\pi(i)})$
1713  * @param kq - (2) from the protocol definition:
1714  *             $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1715  * @param s - S from the protocol definition:
1716  *            $S := E_A(\sum (r_i + b_i)^2)$
1717  * @param stick - S' from the protocol definition:
1718  *                $S' := E_A(\sum r_i^2)$
1719  * @return product as MPI, never NULL
1720  */
1721 static gcry_mpi_t
1722 compute_scalar_product (struct ServiceSession * session)
1723 {
1724   uint32_t count;
1725   gcry_mpi_t t;
1726   gcry_mpi_t u;
1727   gcry_mpi_t utick;
1728   gcry_mpi_t p;
1729   gcry_mpi_t ptick;
1730   gcry_mpi_t tmp;
1731   unsigned int i;
1732
1733   count = session->used_element_count;
1734   tmp = gcry_mpi_new (KEYBITS);
1735   // due to the introduced static offset S, we now also have to remove this
1736   // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1737   // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1738   for (i = 0; i < count; i++) {
1739     decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1740     gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1741     gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1742     decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1743     gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1744     gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1745   }
1746
1747   // calculate t = sum(ai)
1748   t = compute_square_sum (session->a, count);
1749
1750   // calculate U
1751   u = gcry_mpi_new (0);
1752   tmp = compute_square_sum (session->r, count);
1753   gcry_mpi_sub (u, u, tmp);
1754   gcry_mpi_release (tmp);
1755
1756   //calculate U'
1757   utick = gcry_mpi_new (0);
1758   tmp = compute_square_sum (session->r_prime, count);
1759   gcry_mpi_sub (utick, utick, tmp);
1760
1761   GNUNET_assert (p = gcry_mpi_new (0));
1762   GNUNET_assert (ptick = gcry_mpi_new (0));
1763
1764   // compute P
1765   decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1766   decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1767
1768   // compute P
1769   gcry_mpi_add (p, session->s, t);
1770   gcry_mpi_add (p, p, u);
1771
1772   // compute P'
1773   gcry_mpi_add (ptick, session->s_prime, t);
1774   gcry_mpi_add (ptick, ptick, utick);
1775
1776   gcry_mpi_release (t);
1777   gcry_mpi_release (u);
1778   gcry_mpi_release (utick);
1779
1780   // compute product
1781   gcry_mpi_sub (p, p, ptick);
1782   gcry_mpi_release (ptick);
1783   tmp = gcry_mpi_set_ui (tmp, 2);
1784   gcry_mpi_div (p, NULL, p, tmp, 0);
1785
1786   gcry_mpi_release (tmp);
1787   for (i = 0; i < count; i++)
1788     gcry_mpi_release (session->a[i]);
1789   GNUNET_free (session->a);
1790   session->a = NULL;
1791
1792   return p;
1793 }
1794
1795 /**
1796  * prepare the response we will send to alice or bobs' clients.
1797  * in Bobs case the product will be NULL.
1798  *
1799  * @param session  the session associated with our client.
1800  */
1801 static void
1802 prepare_client_response (void *cls,
1803                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1804 {
1805   struct ServiceSession * session = cls;
1806   struct GNUNET_SCALARPRODUCT_client_response * msg;
1807   unsigned char * product_exported = NULL;
1808   size_t product_length = 0;
1809   uint32_t msg_length = 0;
1810   int8_t range = -1;
1811   gcry_error_t rc;
1812   int sign;
1813
1814   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1815
1816   if (session->product) {
1817     gcry_mpi_t value = gcry_mpi_new (0);
1818
1819     sign = gcry_mpi_cmp_ui (session->product, 0);
1820     // libgcrypt can not handle a print of a negative number
1821     // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1822     if (0 > sign) {
1823       gcry_mpi_sub (value, value, session->product);
1824     }
1825     else if (0 < sign) {
1826       range = 1;
1827       gcry_mpi_add (value, value, session->product);
1828     }
1829     else
1830       range = 0;
1831
1832     gcry_mpi_release (session->product);
1833     session->product = NULL;
1834
1835     // get representation as string
1836     if (range
1837         && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
1838                                         &product_exported,
1839                                         &product_length,
1840                                         value)))) {
1841       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1842       product_length = 0;
1843       range = -1; // signal error with product-length = 0 and range = -1
1844     }
1845     gcry_mpi_release (value);
1846   }
1847
1848   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
1849   msg = GNUNET_malloc (msg_length);
1850   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1851   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1852   if (product_exported != NULL) {
1853     memcpy (&msg[1], product_exported, product_length);
1854     GNUNET_free (product_exported);
1855   }
1856   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1857   msg->header.size = htons (msg_length);
1858   msg->range = range;
1859   msg->product_length = htonl (product_length);
1860
1861   session->msg = (struct GNUNET_MessageHeader *) msg;
1862   //transmit this message to our client
1863   session->client_transmit_handle =
1864           GNUNET_SERVER_notify_transmit_ready (session->client,
1865                                                msg_length,
1866                                                GNUNET_TIME_UNIT_FOREVER_REL,
1867                                                &do_send_message,
1868                                                session);
1869   if (NULL == session->client_transmit_handle) {
1870     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1871                 _ ("Could not send message to client (%p)!\n"),
1872                 session->client);
1873     session->client = NULL;
1874     // callback was not called!
1875     GNUNET_free (msg);
1876     session->msg = NULL;
1877   }
1878   else
1879     // gracefully sent message, just terminate session structure
1880     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1881                 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
1882                 session->client,
1883                 GNUNET_h2s (&session->key));
1884 }
1885
1886 /**
1887  * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1888  *
1889  * @param cls closure (set from #GNUNET_MESH_connect)
1890  * @param tunnel connection to the other end
1891  * @param tunnel_ctx place to store local state associated with the tunnel
1892  * @param sender who sent the message
1893  * @param message the actual message
1894  * @param atsi performance data for the connection
1895  * @return #GNUNET_OK to keep the connection open,
1896  *         #GNUNET_SYSERR to close it (signal serious error)
1897  */
1898 static int
1899 handle_service_request_multipart (void *cls,
1900                                   struct GNUNET_MESH_Tunnel * tunnel,
1901                                   void **tunnel_ctx,
1902                                   const struct GNUNET_MessageHeader * message)
1903 {
1904   struct ServiceSession * session;
1905   const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1906   uint32_t used_elements;
1907   uint32_t contained_elements=0;
1908   uint32_t msg_length;
1909   unsigned char * current;
1910   int32_t i = -1;
1911  
1912   // are we in the correct state?
1913   session = (struct ServiceSession *) * tunnel_ctx;
1914   if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
1915     GNUNET_break_op (0);
1916     return GNUNET_OK;
1917   }
1918   // shorter than minimum?
1919   if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
1920     goto except;
1921   }
1922   used_elements = session->used_element_count;
1923   contained_elements = ntohl (msg->multipart_element_count);
1924   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
1925           + contained_elements * PAILLIER_ELEMENT_LENGTH;
1926   //sanity check
1927   if (( ntohs (msg->header.size) != msg_length) 
1928        || (used_elements < contained_elements + session->transferred_element_count)) {
1929     goto except;
1930   }
1931   current = (unsigned char *) &msg[1];
1932   if (contained_elements != 0) {
1933     gcry_error_t ret = 0;
1934     // Convert each vector element to MPI_value
1935     for (i = session->transferred_element_count; i < session->transferred_element_count+contained_elements; i++) {
1936       size_t read = 0;
1937
1938       ret = gcry_mpi_scan (&session->a[i],
1939                            GCRYMPI_FMT_USG,
1940                            &current[i * PAILLIER_ELEMENT_LENGTH],
1941                            PAILLIER_ELEMENT_LENGTH,
1942                            &read);
1943       if (ret) {
1944         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1945                     i, gcry_strsource (ret), gcry_strerror (ret));
1946         goto except;
1947       }
1948     }
1949     session->transferred_element_count+=contained_elements;
1950     
1951     if (session->transferred_element_count == used_elements) {
1952       // single part finished
1953       session->state = SERVICE_REQUEST_RECEIVED;
1954       if (session->response) {
1955         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1956         if (GNUNET_OK != compute_service_response (session, session->response)) {
1957           //something went wrong, remove it again...
1958           GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1959           goto except;
1960         }
1961       }
1962       else
1963         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1964     }
1965     else{
1966       // multipart message
1967     }
1968   }
1969   
1970   return GNUNET_OK;
1971 except:
1972   for (i = 0; i < session->transferred_element_count + contained_elements; i++)
1973     if (session->a[i])
1974       gcry_mpi_release (session->a[i]);
1975   gcry_sexp_release (session->remote_pubkey);
1976   session->remote_pubkey = NULL;
1977   GNUNET_free (session->a);
1978   session->a = NULL;
1979   free_session (session);
1980   // and notify our client-session that we could not complete the session
1981   if (session->response)
1982     // we just found the responder session in this queue
1983     session->response->client_notification_task =
1984           GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1985                                     session->response);
1986   return GNUNET_SYSERR;
1987 }
1988
1989 /**
1990  * Handle a request from another service to calculate a scalarproduct with us.
1991  *
1992  * @param cls closure (set from #GNUNET_MESH_connect)
1993  * @param tunnel connection to the other end
1994  * @param tunnel_ctx place to store local state associated with the tunnel
1995  * @param sender who sent the message
1996  * @param message the actual message
1997  * @param atsi performance data for the connection
1998  * @return #GNUNET_OK to keep the connection open,
1999  *         #GNUNET_SYSERR to close it (signal serious error)
2000  */
2001 static int
2002 handle_service_request (void *cls,
2003                         struct GNUNET_MESH_Tunnel * tunnel,
2004                         void **tunnel_ctx,
2005                         const struct GNUNET_MessageHeader * message)
2006 {
2007   struct ServiceSession * session;
2008   const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2009   uint32_t mask_length;
2010   uint32_t pk_length;
2011   uint32_t used_elements;
2012   uint32_t contained_elements;
2013   uint32_t element_count;
2014   uint32_t msg_length;
2015   unsigned char * current;
2016   int32_t i = -1;
2017   enum SessionState needed_state;
2018
2019   session = (struct ServiceSession *) * tunnel_ctx;
2020   if (WAITING_FOR_SERVICE_REQUEST != session->state) {
2021     GNUNET_break_op (0);
2022     return GNUNET_OK;
2023   }
2024   // Check if message was sent by me, which would be bad!
2025   if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2026     GNUNET_free (session);
2027     GNUNET_break (0);
2028     return GNUNET_SYSERR;
2029   }
2030   // shorter than expected?
2031   if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2032     GNUNET_free (session);
2033     GNUNET_break_op (0);
2034     return GNUNET_SYSERR;
2035   }
2036   mask_length = ntohl (msg->mask_length);
2037   pk_length = ntohl (msg->pk_length);
2038   used_elements = ntohl (msg->total_element_count);
2039   contained_elements = ntohl (msg->contained_element_count);
2040   element_count = ntohl (msg->element_count);
2041   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2042           +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2043
2044   //sanity check: is the message as long as the message_count fields suggests?
2045   if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2046       || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2047       ) {
2048     GNUNET_free (session);
2049     GNUNET_break_op (0);
2050     return GNUNET_SYSERR;
2051   }
2052   if (find_matching_session (from_service_tail,
2053                              &msg->key,
2054                              element_count,
2055                              NULL,
2056                              NULL)) {
2057     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2058     GNUNET_free (session);
2059     return GNUNET_SYSERR;
2060   }
2061
2062   memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
2063   session->element_count = element_count;
2064   session->used_element_count = used_elements;
2065   session->transferred_element_count = contained_elements;
2066   session->tunnel = tunnel;
2067
2068   // session key
2069   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2070   current = (unsigned char *) &msg[1];
2071   //preserve the mask, we will need that later on
2072   session->mask = GNUNET_malloc (mask_length);
2073   memcpy (session->mask, current, mask_length);
2074   //the public key
2075   current += mask_length;
2076
2077   //convert the publickey to sexp
2078   if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1)) {
2079     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
2080     GNUNET_free (session->mask);
2081     GNUNET_free (session);
2082     return GNUNET_SYSERR;
2083   }
2084
2085   current += pk_length;
2086
2087   //check if service queue contains a matching request
2088   needed_state = CLIENT_RESPONSE_RECEIVED;
2089   session->response = find_matching_session (from_client_tail,
2090                                              &session->key,
2091                                              session->element_count,
2092                                              &needed_state, NULL);
2093
2094   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2095   session->state = WAITING_FOR_MULTIPART_TRANSMISSION; 
2096   if (contained_elements != 0) {
2097     gcry_error_t ret = 0;
2098     // Convert each vector element to MPI_value
2099     for (i = 0; i < contained_elements; i++) {
2100       size_t read = 0;
2101
2102       ret = gcry_mpi_scan (&session->a[i],
2103                            GCRYMPI_FMT_USG,
2104                            &current[i * PAILLIER_ELEMENT_LENGTH],
2105                            PAILLIER_ELEMENT_LENGTH,
2106                            &read);
2107       if (ret) {
2108         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
2109                     i, gcry_strsource (ret), gcry_strerror (ret));
2110         goto except;
2111       }
2112     }
2113     GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2114     
2115     if (contained_elements == used_elements) {
2116       // single part finished
2117       session->state = SERVICE_REQUEST_RECEIVED;
2118       if (session->response) {
2119         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2120         if (GNUNET_OK != compute_service_response (session, session->response)) {
2121           //something went wrong, remove it again...
2122           GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2123           goto except;
2124         }
2125       }
2126       else
2127         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2128     }
2129     else{
2130       // multipart message
2131     }
2132   }
2133   return GNUNET_OK;
2134 except:
2135   for (i = 0; i < contained_elements; i++)
2136     if (session->a[i])
2137       gcry_mpi_release (session->a[i]);
2138   gcry_sexp_release (session->remote_pubkey);
2139   session->remote_pubkey = NULL;
2140   GNUNET_free (session->a);
2141   session->a = NULL;
2142   free_session (session);
2143   // and notify our client-session that we could not complete the session
2144   if (session->response)
2145     // we just found the responder session in this queue
2146     session->response->client_notification_task =
2147           GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2148                                     session->response);
2149   return GNUNET_SYSERR;
2150 }
2151
2152 /**
2153  * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2154  *
2155  * @param cls closure (set from #GNUNET_MESH_connect)
2156  * @param tunnel connection to the other end
2157  * @param tunnel_ctx place to store local state associated with the tunnel
2158  * @param sender who sent the message
2159  * @param message the actual message
2160  * @param atsi performance data for the connection
2161  * @return #GNUNET_OK to keep the connection open,
2162  *         #GNUNET_SYSERR to close it (signal serious error)
2163  */
2164 static int
2165 handle_service_response_multipart (void *cls,
2166                                    struct GNUNET_MESH_Tunnel * tunnel,
2167                                    void **tunnel_ctx,
2168                                    const struct GNUNET_MessageHeader * message)
2169 {
2170   struct ServiceSession * session;
2171   const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2172   unsigned char * current;
2173   size_t read;
2174   size_t i;
2175   uint32_t contained_element_count=0;
2176   size_t msg_size;
2177   int rc;
2178
2179   GNUNET_assert (NULL != message);
2180   // are we in the correct state?
2181   session = (struct ServiceSession *) * tunnel_ctx;
2182   if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2183     GNUNET_break_op (0);
2184     return GNUNET_OK;
2185   }
2186   // shorter than minimum?
2187   if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2188     goto except;
2189   }
2190   contained_element_count = ntohl (msg->multipart_element_count);
2191   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2192           + 2 * contained_element_count * PAILLIER_ELEMENT_LENGTH;
2193   //sanity check: is the message as long as the message_count fields suggests?
2194   if ((ntohs (msg->header.size) != msg_size) || (session->used_element_count < contained_element_count)) {
2195     goto except;
2196   }
2197   current = (unsigned char *) &msg[1];
2198   // Convert each k[][perm] to its MPI_value
2199   for (i = 0; i < contained_element_count; i++) {
2200     if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2201                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2202       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2203       GNUNET_break_op (0);
2204       goto except;
2205     }
2206     current += PAILLIER_ELEMENT_LENGTH;
2207     if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2208                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2209       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2210       GNUNET_break_op (0);
2211       goto except;
2212     }
2213     current += PAILLIER_ELEMENT_LENGTH;
2214   }
2215   session->transferred_element_count += contained_element_count;
2216   if (session->transferred_element_count != session->used_element_count)
2217     return GNUNET_OK;
2218   session->state = SERVICE_RESPONSE_RECEIVED;
2219   session->product = compute_scalar_product (session);
2220   return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2221 except:
2222   GNUNET_break_op (0);
2223   if (session->s)
2224     gcry_mpi_release (session->s);
2225   if (session->s_prime)
2226     gcry_mpi_release (session->s_prime);
2227   for (i = 0; session->r && i < session->transferred_element_count; i++)
2228     if (session->r[i]) gcry_mpi_release (session->r[i]);
2229   for (i = 0; session->r_prime && i < session->transferred_element_count; i++)
2230     if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2231   GNUNET_free_non_null (session->r);
2232   GNUNET_free_non_null (session->r_prime);
2233
2234   session->tunnel = NULL;
2235   // send message with product to client
2236   session->client_notification_task =
2237           GNUNET_SCHEDULER_add_now (&prepare_client_response,
2238                                     session);
2239   // the tunnel has done its job, terminate our connection and the tunnel
2240   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2241   // just close the connection, as recommended by Christian
2242   return GNUNET_SYSERR;
2243 }
2244
2245 /**
2246  * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2247  *
2248  * @param cls closure (set from #GNUNET_MESH_connect)
2249  * @param tunnel connection to the other end
2250  * @param tunnel_ctx place to store local state associated with the tunnel
2251  * @param sender who sent the message
2252  * @param message the actual message
2253  * @param atsi performance data for the connection
2254  * @return #GNUNET_OK to keep the connection open,
2255  *         #GNUNET_SYSERR to close it (we are done)
2256  */
2257 static int
2258 handle_service_response (void *cls,
2259                          struct GNUNET_MESH_Tunnel * tunnel,
2260                          void **tunnel_ctx,
2261                          const struct GNUNET_MessageHeader * message)
2262 {
2263   struct ServiceSession * session;
2264   const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2265   unsigned char * current;
2266   size_t read;
2267   size_t i;
2268   uint32_t contained_element_count=0;
2269   size_t msg_size;
2270   int rc;
2271
2272   GNUNET_assert (NULL != message);
2273   session = (struct ServiceSession *) * tunnel_ctx;
2274   if (session->state != WAITING_FOR_SERVICE_REQUEST) {
2275     GNUNET_break_op (0);
2276     return GNUNET_OK;
2277   }
2278   //we need at least a full message
2279   if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size)) {
2280     GNUNET_break_op (0);
2281     goto invalid_msg;
2282   }
2283   contained_element_count = ntohl (msg->contained_element_count);
2284   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2285           + 2 * contained_element_count * PAILLIER_ELEMENT_LENGTH
2286           + 2 * PAILLIER_ELEMENT_LENGTH;
2287   //sanity check: is the message as long as the message_count fields suggests?
2288   if ((ntohs (msg->header.size) != msg_size) || (session->used_element_count < contained_element_count)) {
2289     GNUNET_break_op (0);
2290     goto invalid_msg;
2291   }
2292   session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2293   session->transferred_element_count = contained_element_count;
2294   //convert s
2295   current = (unsigned char *) &msg[1];
2296   if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2297                                 PAILLIER_ELEMENT_LENGTH, &read))) {
2298     LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2299     GNUNET_break_op (0);
2300     goto invalid_msg;
2301   }
2302   current += PAILLIER_ELEMENT_LENGTH;
2303   //convert stick
2304   if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2305                                 PAILLIER_ELEMENT_LENGTH, &read))) {
2306     LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2307     GNUNET_break_op (0);
2308     goto invalid_msg;
2309   }
2310   current += PAILLIER_ELEMENT_LENGTH;
2311   session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
2312   session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
2313   // Convert each k[][perm] to its MPI_value
2314   for (i = 0; i < contained_element_count; i++) {
2315     if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2316                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2317       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2318       GNUNET_break_op (0);
2319       goto invalid_msg;
2320     }
2321     current += PAILLIER_ELEMENT_LENGTH;
2322     if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2323                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2324       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2325       GNUNET_break_op (0);
2326       goto invalid_msg;
2327     }
2328     current += PAILLIER_ELEMENT_LENGTH;
2329   }
2330   if (session->transferred_element_count != session->used_element_count)
2331     return GNUNET_OK; //wait for the other multipart chunks
2332   
2333   session->state = SERVICE_RESPONSE_RECEIVED;
2334   session->product = compute_scalar_product (session);
2335   return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2336
2337 invalid_msg:
2338   if (session->s)
2339     gcry_mpi_release (session->s);
2340   if (session->s_prime)
2341     gcry_mpi_release (session->s_prime);
2342   for (i = 0; session->r && i < contained_element_count; i++)
2343     if (session->r[i]) gcry_mpi_release (session->r[i]);
2344   for (i = 0; session->r_prime && i < contained_element_count; i++)
2345     if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
2346   GNUNET_free_non_null (session->r);
2347   GNUNET_free_non_null (session->r_prime);
2348
2349   session->tunnel = NULL;
2350   // send message with product to client
2351   session->client_notification_task =
2352           GNUNET_SCHEDULER_add_now (&prepare_client_response,
2353                                     session);
2354   // the tunnel has done its job, terminate our connection and the tunnel
2355   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2356   // just close the connection, as recommended by Christian
2357   return GNUNET_SYSERR;
2358 }
2359
2360 /**
2361  * Task run during shutdown.
2362  *
2363  * @param cls unused
2364  * @param tc unused
2365  */
2366 static void
2367 shutdown_task (void *cls,
2368                const struct GNUNET_SCHEDULER_TaskContext *tc)
2369 {
2370   struct ServiceSession * session;
2371   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2372
2373   do_shutdown = GNUNET_YES;
2374
2375   // terminate all owned open tunnels.
2376   for (session = from_client_head; NULL != session; session = session->next) {
2377     if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2378       GNUNET_MESH_tunnel_destroy (session->tunnel);
2379       session->tunnel = NULL;
2380     }
2381     if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2382       GNUNET_SCHEDULER_cancel (session->client_notification_task);
2383       session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2384     }
2385     if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2386       GNUNET_SCHEDULER_cancel (session->service_request_task);
2387       session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2388     }
2389     if (NULL != session->client) {
2390       GNUNET_SERVER_client_disconnect (session->client);
2391       session->client = NULL;
2392     }
2393   }
2394   for (session = from_service_head; NULL != session; session = session->next)
2395     if (NULL != session->tunnel) {
2396       GNUNET_MESH_tunnel_destroy (session->tunnel);
2397       session->tunnel = NULL;
2398     }
2399
2400   if (my_mesh) {
2401     GNUNET_MESH_disconnect (my_mesh);
2402     my_mesh = NULL;
2403   }
2404 }
2405
2406 /**
2407  * Initialization of the program and message handlers
2408  *
2409  * @param cls closure
2410  * @param server the initialized server
2411  * @param c configuration to use
2412  */
2413 static void
2414 run (void *cls,
2415      struct GNUNET_SERVER_Handle *server,
2416      const struct GNUNET_CONFIGURATION_Handle *c)
2417 {
2418   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2419     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2420     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2421     {NULL, NULL, 0, 0}
2422   };
2423   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2424     { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2425     { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2426     { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2427     { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2428     {NULL, 0, 0}
2429   };
2430   static const uint32_t ports[] = {
2431     GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2432     0
2433   };
2434   //generate private/public key set
2435   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2436   generate_keyset ();
2437   // register server callbacks and disconnect handler
2438   GNUNET_SERVER_add_handlers (server, server_handlers);
2439   GNUNET_SERVER_disconnect_notify (server,
2440                                    &handle_client_disconnect,
2441                                    NULL);
2442   GNUNET_break (GNUNET_OK ==
2443                 GNUNET_CRYPTO_get_peer_identity (c,
2444                                                  &me));
2445   my_mesh = GNUNET_MESH_connect (c, NULL,
2446                                  &tunnel_incoming_handler,
2447                                  &tunnel_destruction_handler,
2448                                  mesh_handlers, ports);
2449   if (!my_mesh) {
2450     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2451     GNUNET_SCHEDULER_shutdown ();
2452     return;
2453   }
2454   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2455   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2456                                 &shutdown_task,
2457                                 NULL);
2458 }
2459
2460 /**
2461  * The main function for the scalarproduct service.
2462  *
2463  * @param argc number of arguments from the command line
2464  * @param argv command line arguments
2465  * @return 0 ok, 1 on error
2466  */
2467 int
2468 main (int argc, char *const *argv)
2469 {
2470   return (GNUNET_OK ==
2471           GNUNET_SERVICE_run (argc, argv,
2472                               "scalarproduct",
2473                               GNUNET_SERVICE_OPTION_NONE,
2474                               &run, NULL)) ? 0 : 1;
2475 }
2476
2477 /* end of gnunet-service-ext.c */