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