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