fixed a double-free
[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     session->a = NULL;
711   }
712   GNUNET_free_non_null (session->mask);
713   if (session->r) {
714     for (i = 0; i < session->used; i++)
715       if (session->r[i]) gcry_mpi_release (session->r[i]);
716     GNUNET_free (session->r);
717     session->r = NULL;
718   }
719   if (session->r_prime) {
720     for (i = 0; i < session->used; i++)
721       if (session->r_prime[i]) gcry_mpi_release (session->r_prime[i]);
722     GNUNET_free (session->r_prime);
723     session->r_prime = NULL;
724   }
725   if (session->s){
726     gcry_mpi_release (session->s);
727   session->s = NULL;
728   }
729   
730   if (session->s_prime){
731     gcry_mpi_release (session->s_prime);
732   session->s_prime = NULL;
733   }
734   
735   if (session->product){
736     gcry_mpi_release (session->product);
737   session->product = NULL;
738   }
739
740   if (session->remote_pubkey){
741     gcry_sexp_release (session->remote_pubkey);
742   session->remote_pubkey = NULL;
743   }
744
745   if (session->vector) {
746     GNUNET_free_non_null (session->vector);
747     session->s = NULL;
748   }
749 }
750 ///////////////////////////////////////////////////////////////////////////////
751 //                      Event and Message Handlers
752 ///////////////////////////////////////////////////////////////////////////////
753
754
755 /**
756  * A client disconnected.
757  *
758  * Remove the associated session(s), release data structures
759  * and cancel pending outgoing transmissions to the client.
760  * if the session has not yet completed, we also cancel Alice's request to Bob.
761  *
762  * @param cls closure, NULL
763  * @param client identification of the client
764  */
765 static void
766 handle_client_disconnect (void *cls,
767                           struct GNUNET_SERVER_Client *client)
768 {
769   struct ServiceSession *session;
770   
771   if (NULL != client)
772     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
773               _ ("Client (%p) disconnected from us.\n"), client);
774   else
775     return;
776
777   session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
778   if (NULL == session)
779     return;
780   GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
781
782   if (!(session->role == BOB && session->state == FINALIZED)) {
783     //we MUST terminate any client message underway
784     if (session->service_transmit_handle && session->tunnel)
785       GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
786     if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
787       GNUNET_MESH_tunnel_destroy (session->tunnel);
788   }
789   if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
790     GNUNET_SCHEDULER_cancel (session->client_notification_task);
791     session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
792   }
793   if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
794     GNUNET_SCHEDULER_cancel (session->service_request_task);
795     session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
796   }
797   if (NULL != session->client_transmit_handle) {
798     GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
799     session->client_transmit_handle = NULL;
800   }
801   free_session_variables (session);
802   GNUNET_free (session);
803 }
804
805
806 /**
807  * Notify the client that the session has succeeded or failed completely.
808  * This message gets sent to
809  * * alice's client if bob disconnected or to
810  * * bob's client if the operation completed or alice disconnected
811  *
812  * @param cls the associated client session
813  * @param tc the task context handed to us by the scheduler, unused
814  */
815 static void
816 prepare_client_end_notification (void * cls,
817                                  const struct GNUNET_SCHEDULER_TaskContext * tc)
818 {
819   struct ServiceSession * session = cls;
820   struct GNUNET_SCALARPRODUCT_client_response * msg;
821
822   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
823
824   msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
825   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
826   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
827   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
828   msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
829   // signal error if not signalized, positive result-range field but zero length.
830   msg->product_length = htonl (0);
831   msg->range = (session->state == FINALIZED) ? 0 : -1;
832
833   session->msg = &msg->header;
834
835   //transmit this message to our client
836   session->client_transmit_handle =
837           GNUNET_SERVER_notify_transmit_ready (session->client,
838                                                sizeof (struct GNUNET_SCALARPRODUCT_client_response),
839                                                GNUNET_TIME_UNIT_FOREVER_REL,
840                                                &do_send_message,
841                                                session);
842
843   // if we could not even queue our request, something is wrong
844   if (NULL == session->client_transmit_handle) {
845     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
846     // usually gets freed by do_send_message
847     session->msg = NULL;
848     GNUNET_free (msg);
849   }
850   else
851     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
852
853 }
854
855
856 /**
857  * prepare the response we will send to alice or bobs' clients.
858  * in Bobs case the product will be NULL.
859  *
860  * @param cls the session associated with our client.
861  * @param tc the task context handed to us by the scheduler, unused
862  */
863 static void
864 prepare_client_response (void *cls,
865                          const struct GNUNET_SCHEDULER_TaskContext *tc)
866 {
867   struct ServiceSession * session = cls;
868   struct GNUNET_SCALARPRODUCT_client_response * msg;
869   unsigned char * product_exported = NULL;
870   size_t product_length = 0;
871   uint32_t msg_length = 0;
872   int8_t range = -1;
873   gcry_error_t rc;
874   int sign;
875
876   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
877
878   if (session->product) {
879     gcry_mpi_t value = gcry_mpi_new (0);
880
881     sign = gcry_mpi_cmp_ui (session->product, 0);
882     // libgcrypt can not handle a print of a negative number
883     // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
884     if (0 > sign) {
885       gcry_mpi_sub (value, value, session->product);
886     }
887     else if (0 < sign) {
888       range = 1;
889       gcry_mpi_add (value, value, session->product);
890     }
891     else
892       range = 0;
893
894     gcry_mpi_release (session->product);
895     session->product = NULL;
896
897     // get representation as string
898     if (range
899         && (0 != (rc = gcry_mpi_aprint (GCRYMPI_FMT_STD,
900                                         &product_exported,
901                                         &product_length,
902                                         value)))) {
903       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
904       product_length = 0;
905       range = -1; // signal error with product-length = 0 and range = -1
906     }
907     gcry_mpi_release (value);
908   }
909
910   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
911   msg = GNUNET_malloc (msg_length);
912   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
913   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
914   if (product_exported != NULL) {
915     memcpy (&msg[1], product_exported, product_length);
916     GNUNET_free (product_exported);
917   }
918   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
919   msg->header.size = htons (msg_length);
920   msg->range = range;
921   msg->product_length = htonl (product_length);
922
923   session->msg = (struct GNUNET_MessageHeader *) msg;
924   //transmit this message to our client
925   session->client_transmit_handle =
926           GNUNET_SERVER_notify_transmit_ready (session->client,
927                                                msg_length,
928                                                GNUNET_TIME_UNIT_FOREVER_REL,
929                                                &do_send_message,
930                                                session);
931   if (NULL == session->client_transmit_handle) {
932     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
933                 _ ("Could not send message to client (%p)!\n"),
934                 session->client);
935     session->client = NULL;
936     // callback was not called!
937     GNUNET_free (msg);
938     session->msg = NULL;
939   }
940   else
941     // gracefully sent message, just terminate session structure
942     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
943                 _ ("Sent result to client (%p), this session (%s) has ended!\n"),
944                 session->client,
945                 GNUNET_h2s (&session->key));
946 }
947
948
949 /**
950  * Send a multipart chunk of a service response from bob to alice.
951  * This element only contains the two permutations of R, R'.
952  * 
953  * @param cls the associated service session
954  */
955 static void
956 prepare_service_response_multipart (void *cls)
957 {
958   struct ServiceSession * session = cls;
959   unsigned char * current;
960   unsigned char * element_exported;
961   struct GNUNET_SCALARPRODUCT_multipart_message * msg;
962   unsigned int i;
963   uint32_t msg_length;
964   uint32_t todo_count;
965   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
966
967   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
968   todo_count = session->used - session->transferred;
969
970   if (todo_count > MULTIPART_ELEMENT_CAPACITY / 2)
971     // send the currently possible maximum chunk, we always transfer both permutations
972     todo_count = MULTIPART_ELEMENT_CAPACITY / 2;
973
974   msg_length += todo_count * PAILLIER_ELEMENT_LENGTH * 2;
975   msg = GNUNET_malloc (msg_length);
976   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
977   msg->header.size = htons (msg_length);
978   msg->multipart_element_count = htonl (todo_count);
979
980   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
981   current = (unsigned char *) &msg[1];
982   // convert k[][]
983   for (i = session->transferred; i < session->transferred + todo_count; i++) {
984     //k[i][p]
985     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
986     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
987                                         element_exported, PAILLIER_ELEMENT_LENGTH,
988                                         &element_length,
989                                         session->r[i]));
990     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
991     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
992     current += PAILLIER_ELEMENT_LENGTH;
993     //k[i][q]
994     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
995     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
996                                         element_exported, PAILLIER_ELEMENT_LENGTH,
997                                         &element_length,
998                                         session->r_prime[i]));
999     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1000     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1001     current += PAILLIER_ELEMENT_LENGTH;
1002   }
1003   GNUNET_free (element_exported);
1004   for (i = session->transferred; i < session->transferred; i++) {
1005     gcry_mpi_release (session->r_prime[i]);
1006     gcry_mpi_release (session->r[i]);
1007   }
1008   session->transferred += todo_count;
1009   session->msg = (struct GNUNET_MessageHeader *) msg;
1010   session->service_transmit_handle =
1011           GNUNET_MESH_notify_transmit_ready (session->tunnel,
1012                                              GNUNET_YES,
1013                                              GNUNET_TIME_UNIT_FOREVER_REL,
1014                                              msg_length,
1015                                              &do_send_message,
1016                                              session);
1017   //disconnect our client
1018   if (NULL == session->service_transmit_handle) {
1019     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1020     session->state = FINALIZED;
1021
1022     session->response->client_notification_task =
1023             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1024                                       session->response);
1025     return;
1026   }
1027   if (session->transferred != session->used)
1028     // more multiparts
1029     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1030   else{
1031     // final part
1032     session->state = FINALIZED;
1033     GNUNET_free(session->r);
1034     GNUNET_free(session->r_prime);
1035     session->r_prime = NULL;
1036     session->r = NULL;
1037   }
1038 }
1039
1040
1041 /**
1042  * Bob executes:
1043  * generates the response message to be sent to alice after computing
1044  * the values (1), (2), S and S'
1045  *  (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)})$
1046  *  (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1047  *      S: $S := E_A(sum (r_i + b_i)^2)$
1048  *     S': $S' := E_A(sum r_i^2)$
1049  *
1050  * @param s         S: $S := E_A(sum (r_i + b_i)^2)$
1051  * @param s_prime    S': $S' := E_A(sum r_i^2)$
1052  * @param session  the associated requesting session with alice
1053  * @return #GNUNET_NO if we could not send our message
1054  *         #GNUNET_OK if the operation succeeded
1055  */
1056 static int
1057 prepare_service_response (gcry_mpi_t s,
1058                           gcry_mpi_t s_prime,
1059                           struct ServiceSession * session)
1060 {
1061   struct GNUNET_SCALARPRODUCT_service_response * msg;
1062   uint32_t msg_length = 0;
1063   unsigned char * current = NULL;
1064   unsigned char * element_exported = NULL;
1065   size_t element_length = 0;
1066   int i;
1067
1068   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
1069           + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
1070
1071   if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + 2 * session->used * PAILLIER_ELEMENT_LENGTH) { //kp, kq
1072     msg_length += +2 * session->used * PAILLIER_ELEMENT_LENGTH;
1073     session->transferred = session->used;
1074   }
1075   else {
1076     session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / (PAILLIER_ELEMENT_LENGTH * 2);
1077   }
1078
1079   msg = GNUNET_malloc (msg_length);
1080
1081   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
1082   msg->header.size = htons (msg_length);
1083   msg->total_element_count = htonl (session->total);
1084   msg->used_element_count = htonl (session->used);
1085   msg->contained_element_count = htonl (session->transferred);
1086   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1087   current = (unsigned char *) &msg[1];
1088
1089   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1090   // 4 times the same logics with slight variations.
1091   // doesn't really justify having 2 functions for that
1092   // so i put it into blocks to enhance readability
1093   // convert s
1094   memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1095   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1096                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1097                                       &element_length,
1098                                       s));
1099   adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1100   memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1101   current += PAILLIER_ELEMENT_LENGTH;
1102
1103   // convert stick
1104   memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1105   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1106                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1107                                       &element_length,
1108                                       s_prime));
1109   adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1110   memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1111   current += PAILLIER_ELEMENT_LENGTH;
1112
1113   // convert k[][]
1114   for (i = 0; i < session->transferred; i++) {
1115     //k[i][p]
1116     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1117     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1118                                         element_exported, PAILLIER_ELEMENT_LENGTH,
1119                                         &element_length,
1120                                         session->r[i]));
1121     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1122     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1123     current += PAILLIER_ELEMENT_LENGTH;
1124     //k[i][q]
1125     memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1126     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1127                                         element_exported, PAILLIER_ELEMENT_LENGTH,
1128                                         &element_length,
1129                                         session->r_prime[i]));
1130     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1131     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1132     current += PAILLIER_ELEMENT_LENGTH;
1133   }
1134
1135   GNUNET_free (element_exported);
1136   for (i = 0; i < session->transferred; i++) {
1137     gcry_mpi_release (session->r_prime[i]);
1138     gcry_mpi_release (session->r[i]);
1139   }
1140   gcry_mpi_release (s);
1141   gcry_mpi_release (s_prime);
1142
1143   session->msg = (struct GNUNET_MessageHeader *) msg;
1144   session->service_transmit_handle =
1145           GNUNET_MESH_notify_transmit_ready (session->tunnel,
1146                                              GNUNET_YES,
1147                                              GNUNET_TIME_UNIT_FOREVER_REL,
1148                                              msg_length,
1149                                              &do_send_message,
1150                                              session);
1151   //disconnect our client
1152   if (NULL == session->service_transmit_handle) {
1153     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
1154     session->state = FINALIZED;
1155
1156     session->response->client_notification_task =
1157             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1158                                       session->response);
1159     return GNUNET_NO;
1160   }
1161   if (session->transferred != session->used)
1162     // multipart
1163     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1164   else{
1165     //singlepart
1166     session->state = FINALIZED;
1167     GNUNET_free(session->r);
1168     GNUNET_free(session->r_prime);
1169     session->r_prime = NULL;
1170     session->r = NULL;
1171   }
1172
1173   return GNUNET_OK;
1174 }
1175
1176
1177 /**
1178  * executed by bob:
1179  * compute the values
1180  *  (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)})$
1181  *  (2)[]: $E_A(a_{pi'(i)}) otimes E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1182  *      S: $S := E_A(sum (r_i + b_i)^2)$
1183  *     S': $S' := E_A(sum r_i^2)$
1184  *
1185  * @param request the requesting session + bob's requesting peer
1186  * @param response the responding session + bob's client handle
1187  * @return GNUNET_SYSERR if the computation failed
1188  *         GNUNET_OK if everything went well.
1189  */
1190 static int
1191 compute_service_response (struct ServiceSession * request,
1192                           struct ServiceSession * response)
1193 {
1194   int i;
1195   int j;
1196   int ret = GNUNET_SYSERR;
1197   unsigned int * p;
1198   unsigned int * q;
1199   uint32_t count;
1200   gcry_mpi_t * rand = NULL;
1201   gcry_mpi_t * r = NULL;
1202   gcry_mpi_t * r_prime = NULL;
1203   gcry_mpi_t * b;
1204   gcry_mpi_t * a_pi;
1205   gcry_mpi_t * a_pi_prime;
1206   gcry_mpi_t * b_pi;
1207   gcry_mpi_t * rand_pi;
1208   gcry_mpi_t * rand_pi_prime;
1209   gcry_mpi_t s = NULL;
1210   gcry_mpi_t s_prime = NULL;
1211   gcry_mpi_t remote_n = NULL;
1212   gcry_mpi_t remote_nsquare;
1213   gcry_mpi_t remote_g = NULL;
1214   gcry_sexp_t tmp_exp;
1215   uint32_t value;
1216
1217   count = request->used;
1218
1219   b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1220   a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1221   b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1222   a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1223   rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1224   rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1225
1226   // convert responder session to from long to mpi
1227   for (i = 0, j = 0; i < response->total && j < count; i++) {
1228     if (request->mask[i / 8] & (1 << (i % 8))) {
1229       value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
1230       // long to gcry_mpi_t
1231       if (0 > response->vector[i]) {
1232         b[j] = gcry_mpi_new (0);
1233         gcry_mpi_sub_ui (b[j], b[j], value);
1234       }
1235       else {
1236         b[j] = gcry_mpi_set_ui (NULL, value);
1237       }
1238       j++;
1239     }
1240   }
1241   GNUNET_free (response->vector);
1242   response->vector = NULL;
1243
1244   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1245   if (!tmp_exp) {
1246     GNUNET_break_op (0);
1247     gcry_sexp_release (request->remote_pubkey);
1248     request->remote_pubkey = NULL;
1249     goto except;
1250   }
1251   remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1252   if (!remote_n) {
1253     GNUNET_break (0);
1254     gcry_sexp_release (tmp_exp);
1255     goto except;
1256   }
1257   remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1258   gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1259   gcry_sexp_release (tmp_exp);
1260   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1261   gcry_sexp_release (request->remote_pubkey);
1262   request->remote_pubkey = NULL;
1263   if (!tmp_exp) {
1264     GNUNET_break_op (0);
1265     gcry_mpi_release (remote_n);
1266     goto except;
1267   }
1268   remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1269   if (!remote_g) {
1270     GNUNET_break (0);
1271     gcry_mpi_release (remote_n);
1272     gcry_sexp_release (tmp_exp);
1273     goto except;
1274   }
1275   gcry_sexp_release (tmp_exp);
1276
1277   // generate r, p and q
1278   rand = initialize_mpi_vector (count);
1279   for (i = 0; i < count; i++) {
1280     value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
1281
1282     // long to gcry_mpi_t
1283     if (value < 0)
1284       gcry_mpi_sub_ui (rand[i],
1285                        rand[i],
1286                        -value);
1287     else
1288       rand[i] = gcry_mpi_set_ui (rand[i], value);
1289   }
1290   p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1291   q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1292   //initialize the result vectors
1293   r = initialize_mpi_vector (count);
1294   r_prime = initialize_mpi_vector (count);
1295
1296   // copy the REFERNCES of a, b and r into aq and bq. we will not change
1297   // those values, thus we can work with the references
1298   memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1299   memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1300   memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1301   memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1302   memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1303
1304   // generate p and q permutations for a, b and r
1305   GNUNET_assert (permute_vector (a_pi, p, count));
1306   GNUNET_assert (permute_vector (b_pi, p, count));
1307   GNUNET_assert (permute_vector (rand_pi, p, count));
1308   GNUNET_assert (permute_vector (a_pi_prime, q, count));
1309   GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1310
1311   // encrypt the element
1312   // for the sake of readability I decided to have dedicated permutation
1313   // vectors, which get rid of all the lookups in p/q.
1314   // however, ap/aq are not absolutely necessary but are just abstraction
1315   // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1316   for (i = 0; i < count; i++) {
1317     // E(S - r_pi - b_pi)
1318     gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1319     gcry_mpi_sub (r[i], r[i], b_pi[i]);
1320     encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1321
1322     // E(S - r_pi - b_pi) * E(S + a_pi) ==  E(2*S + a - r - b)
1323     gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1324   }
1325   GNUNET_free (a_pi);
1326   GNUNET_free (b_pi);
1327   GNUNET_free (rand_pi);
1328
1329   // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1330   for (i = 0; i < count; i++) {
1331     // E(S - r_qi)
1332     gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1333     encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1334
1335     // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1336     gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1337   }
1338   GNUNET_free (a_pi_prime);
1339   GNUNET_free (rand_pi_prime);
1340
1341   request->r = r;
1342   request->r_prime = r_prime;
1343   request->response = response;
1344
1345   // Calculate S' =  E(SUM( r_i^2 ))
1346   s_prime = compute_square_sum (rand, count);
1347   encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1348
1349   // Calculate S = E(SUM( (r_i + b_i)^2 ))
1350   for (i = 0; i < count; i++) {
1351     gcry_mpi_add (rand[i], rand[i], b[i]);
1352   }
1353   s = compute_square_sum (rand, count);
1354   encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1355   gcry_mpi_release (remote_n);
1356   gcry_mpi_release (remote_g);
1357   gcry_mpi_release (remote_nsquare);
1358
1359   // release r and tmp
1360   for (i = 0; i < count; i++)
1361     // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1362     gcry_mpi_release (rand[i]);
1363
1364   // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
1365   if (GNUNET_YES != prepare_service_response (s, s_prime, request))
1366     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1367                 GNUNET_i2s (&request->peer));
1368   else
1369     ret = GNUNET_OK;
1370
1371 except:
1372   for (i = 0; i < count; i++) {
1373     gcry_mpi_release (b[i]);
1374     gcry_mpi_release (request->a[i]);
1375   }
1376
1377   GNUNET_free (b);
1378   GNUNET_free (request->a);
1379   request->a = NULL;
1380
1381   return ret;
1382 }
1383
1384
1385 /**
1386  * Send a multi part chunk of a service request from alice to bob.
1387  * This element only contains a part of the elements-vector (session->a[]),
1388  * mask and public key set have to be contained within the first message
1389  * 
1390  * This allows a ~32kbit key length while using 32000 elements or 62000 elements per request.
1391  * 
1392  * @param cls the associated service session
1393  */
1394 static void
1395 prepare_service_request_multipart (void *cls)
1396 {
1397   struct ServiceSession * session = cls;
1398   unsigned char * current;
1399   unsigned char * element_exported;
1400   struct GNUNET_SCALARPRODUCT_multipart_message * msg;
1401   unsigned int i;
1402   unsigned int j;
1403   uint32_t msg_length;
1404   uint32_t todo_count;
1405   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1406   gcry_mpi_t a;
1407   uint32_t value;
1408
1409   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message);
1410   todo_count = session->used - session->transferred;
1411
1412   if (todo_count > MULTIPART_ELEMENT_CAPACITY)
1413     // send the currently possible maximum chunk
1414     todo_count = MULTIPART_ELEMENT_CAPACITY;
1415
1416   msg_length += todo_count * PAILLIER_ELEMENT_LENGTH;
1417   msg = GNUNET_malloc (msg_length);
1418   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART);
1419   msg->header.size = htons (msg_length);
1420   msg->multipart_element_count = htonl (todo_count);
1421
1422   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1423   a = gcry_mpi_new (KEYBITS * 2);
1424   current = (unsigned char *) &msg[1];
1425   // encrypt our vector and generate string representations
1426   for (i = session->last_processed, j = 0; i < session->total; i++) {
1427     // is this a used element?
1428     if (session->mask[i / 8] & 1 << (i % 8)) {
1429       if (todo_count <= j)
1430         break; //reached end of this message, can't include more
1431
1432       memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1433       value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1434
1435       a = gcry_mpi_set_ui (a, 0);
1436       // long to gcry_mpi_t
1437       if (session->vector[i] < 0)
1438         gcry_mpi_sub_ui (a, a, value);
1439       else
1440         gcry_mpi_add_ui (a, a, value);
1441
1442       session->a[session->transferred + j++] = gcry_mpi_set (NULL, a);
1443       gcry_mpi_add (a, a, my_offset);
1444       encrypt_element (a, a, my_g, my_n, my_nsquare);
1445
1446       // get representation as string
1447       // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1448       GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1449                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1450                                       &element_length,
1451                                       a));
1452
1453       // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1454       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1455
1456       // copy over to the message
1457       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1458       current += PAILLIER_ELEMENT_LENGTH;
1459     }
1460   }
1461   gcry_mpi_release (a);
1462   GNUNET_free (element_exported);
1463   session->transferred += todo_count;
1464
1465   session->msg = (struct GNUNET_MessageHeader *) msg;
1466   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1467
1468   //transmit via mesh messaging
1469   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1470                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1471                                                                         msg_length,
1472                                                                         &do_send_message,
1473                                                                         session);
1474   if (!session->service_transmit_handle) {
1475     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-request multipart message to tunnel!\n"));
1476     GNUNET_free (msg);
1477     session->msg = NULL;
1478     session->client_notification_task =
1479             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1480                                       session);
1481     return;
1482   }
1483   if (session->transferred != session->used) {
1484     session->last_processed = i;
1485   }
1486   else
1487     //final part
1488     session->state = WAITING_FOR_SERVICE_RESPONSE;
1489 }
1490
1491
1492 /**
1493  * Executed by Alice, fills in a service-request message and sends it to the given peer
1494  *
1495  * @param cls the session associated with this request
1496  * @param tc task context handed over by scheduler, unsued
1497  */
1498 static void
1499 prepare_service_request (void *cls,
1500                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1501 {
1502   struct ServiceSession * session = cls;
1503   unsigned char * current;
1504   unsigned char * element_exported;
1505   struct GNUNET_SCALARPRODUCT_service_request * msg;
1506   unsigned int i;
1507   unsigned int j;
1508   uint32_t msg_length;
1509   size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
1510   gcry_mpi_t a;
1511   uint32_t value;
1512
1513   session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1514
1515   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
1516
1517   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1518           +session->mask_length
1519           + my_pubkey_external_length;
1520
1521   if (GNUNET_SERVER_MAX_MESSAGE_SIZE > msg_length + session->used * PAILLIER_ELEMENT_LENGTH) {
1522     msg_length += session->used * PAILLIER_ELEMENT_LENGTH;
1523     session->transferred = session->used;
1524   }
1525   else {
1526     //create a multipart msg, first we calculate a new msg size for the head msg
1527     session->transferred = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - msg_length) / PAILLIER_ELEMENT_LENGTH;
1528   }
1529
1530   msg = GNUNET_malloc (msg_length);
1531   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1532   msg->total_element_count = htonl (session->used);
1533   msg->contained_element_count = htonl (session->transferred);
1534   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1535   msg->mask_length = htonl (session->mask_length);
1536   msg->pk_length = htonl (my_pubkey_external_length);
1537   msg->element_count = htonl (session->total);
1538   msg->header.size = htons (msg_length);
1539
1540   // fill in the payload
1541   current = (unsigned char *) &msg[1];
1542   // copy over the mask
1543   memcpy (current, session->mask, session->mask_length);
1544   // copy over our public key
1545   current += session->mask_length;
1546   memcpy (current, my_pubkey_external, my_pubkey_external_length);
1547   current += my_pubkey_external_length;
1548
1549   // now copy over the element vector
1550   element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1551   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
1552   a = gcry_mpi_new (KEYBITS * 2);
1553   // encrypt our vector and generate string representations
1554   for (i = 0, j = 0; i < session->total; i++) {
1555     // if this is a used element...
1556     if (session->mask[i / 8] & 1 << (i % 8)) {
1557       if (session->transferred <= j)
1558         break; //reached end of this message, can't include more
1559
1560       memset (element_exported, 0, PAILLIER_ELEMENT_LENGTH);
1561       value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1562
1563       a = gcry_mpi_set_ui (a, 0);
1564       // long to gcry_mpi_t
1565       if (session->vector[i] < 0)
1566         gcry_mpi_sub_ui (a, a, value);
1567       else
1568         gcry_mpi_add_ui (a, a, value);
1569
1570       session->a[j++] = gcry_mpi_set (NULL, a);
1571       gcry_mpi_add (a, a, my_offset);
1572       encrypt_element (a, a, my_g, my_n, my_nsquare);
1573
1574       // get representation as string
1575       // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1576       GNUNET_assert (!gcry_mpi_print (GCRYMPI_FMT_USG,
1577                                       element_exported, PAILLIER_ELEMENT_LENGTH,
1578                                       &element_length,
1579                                       a));
1580
1581       // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1582       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1583
1584       // copy over to the message
1585       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1586       current += PAILLIER_ELEMENT_LENGTH;
1587     }
1588   }
1589   gcry_mpi_release (a);
1590   GNUNET_free (element_exported);
1591
1592   session->msg = (struct GNUNET_MessageHeader *) msg;
1593   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Transmitting service request.\n"));
1594
1595   //transmit via mesh messaging
1596   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1597                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1598                                                                         msg_length,
1599                                                                         &do_send_message,
1600                                                                         session);
1601   if (!session->service_transmit_handle) {
1602     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send message to tunnel!\n"));
1603     GNUNET_free (msg);
1604     session->msg = NULL;
1605     session->client_notification_task =
1606             GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1607                                       session);
1608     return;
1609   }
1610   if (session->transferred != session->used) {
1611     session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
1612     session->last_processed = i;
1613   }
1614   else
1615     //singlepart message
1616     session->state = WAITING_FOR_SERVICE_RESPONSE;
1617 }
1618
1619
1620 /**
1621  * Handler for a client request message.
1622  * Can either be type A or B
1623  *   A: request-initiation to compute a scalar product with a peer
1624  *   B: response role, keep the values + session and wait for a matching session or process a waiting request
1625  *
1626  * @param cls closure
1627  * @param client identification of the client
1628  * @param message the actual message
1629  */
1630 static void
1631 handle_client_request (void *cls,
1632                        struct GNUNET_SERVER_Client *client,
1633                        const struct GNUNET_MessageHeader *message)
1634 {
1635   const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1636   struct ServiceSession * session;
1637   uint32_t element_count;
1638   uint32_t mask_length;
1639   uint32_t msg_type;
1640   int32_t * vector;
1641   uint32_t i;
1642
1643   // only one concurrent session per client connection allowed, simplifies logics a lot...
1644   session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
1645   if ((NULL != session) && (session->state != FINALIZED)) {
1646     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1647     return;
1648   }
1649   else if (NULL != session) {
1650     // old session is already completed, clean it up
1651     GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1652     free_session_variables (session);
1653     GNUNET_free (session);
1654   }
1655
1656   //we need at least a peer and one message id to compare
1657   if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size)) {
1658     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1659                 _ ("Too short message received from client!\n"));
1660     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1661     return;
1662   }
1663
1664   msg_type = ntohs (msg->header.type);
1665   element_count = ntohl (msg->element_count);
1666   mask_length = ntohl (msg->mask_length);
1667
1668   //sanity check: is the message as long as the message_count fields suggests?
1669   if ((ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) +element_count * sizeof (int32_t) + mask_length))
1670       || (0 == element_count)) {
1671     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1672                 _ ("Invalid message received from client, session information incorrect!\n"));
1673     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1674     return;
1675   }
1676
1677   // do we have a duplicate session here already?
1678   if (NULL != find_matching_session (from_client_tail,
1679                                      &msg->key,
1680                                      element_count,
1681                                      NULL, NULL)) {
1682     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1683                 _ ("Duplicate session information received, cannot create new session with key `%s'\n"),
1684                 GNUNET_h2s (&msg->key));
1685     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1686     return;
1687   }
1688
1689   session = GNUNET_new (struct ServiceSession);
1690   session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
1691   session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
1692   session->client = client;
1693   session->total = element_count;
1694   session->mask_length = mask_length;
1695   // get our transaction key
1696   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1697   //allocate memory for vector and encrypted vector
1698   session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1699   vector = (int32_t *) & msg[1];
1700
1701   if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type) {
1702     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703                 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"),
1704                 GNUNET_h2s (&session->key));
1705
1706     session->role = ALICE;
1707     // fill in the mask
1708     session->mask = GNUNET_malloc (mask_length);
1709     memcpy (session->mask, &vector[element_count], mask_length);
1710
1711     // copy over the elements
1712     session->used = 0;
1713     for (i = 0; i < element_count; i++) {
1714       session->vector[i] = ntohl (vector[i]);
1715       if (session->vector[i] == 0)
1716         session->mask[i / 8] &= ~(1 << (i % 8));
1717       if (session->mask[i / 8] & (1 << (i % 8)))
1718         session->used++;
1719     }
1720
1721     if (0 == session->used) {
1722       GNUNET_break_op (0);
1723       GNUNET_free (session->vector);
1724       GNUNET_free (session);
1725       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1726       return;
1727     }
1728     //session with ourself makes no sense!
1729     if (!memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
1730       GNUNET_break (0);
1731       GNUNET_free (session->vector);
1732       GNUNET_free (session);
1733       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1734       return;
1735     }
1736     // get our peer ID
1737     memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1738     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1739                 _ ("Creating new tunnel for session with key %s.\n"),
1740                 GNUNET_h2s (&session->key));
1741     session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1742                                                  &session->peer,
1743                                                  GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1744                                                  GNUNET_NO,
1745                                                  GNUNET_YES);
1746     //prepare_service_request, tunnel_peer_disconnect_handler,
1747     if (!session->tunnel) {
1748       GNUNET_break (0);
1749       GNUNET_free (session->vector);
1750       GNUNET_free (session);
1751       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1752       return;
1753     }
1754     GNUNET_SERVER_client_set_user_context (client, session);
1755     GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1756
1757     session->state = CLIENT_REQUEST_RECEIVED;
1758     session->service_request_task =
1759             GNUNET_SCHEDULER_add_now (&prepare_service_request,
1760                                       session);
1761
1762   }
1763   else {
1764     struct ServiceSession * requesting_session;
1765     enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
1766
1767     session->role = BOB;
1768     session->mask = NULL;
1769     // copy over the elements
1770     session->used = element_count;
1771     for (i = 0; i < element_count; i++)
1772       session->vector[i] = ntohl (vector[i]);
1773     session->state = CLIENT_RESPONSE_RECEIVED;
1774
1775     GNUNET_SERVER_client_set_user_context (client, session);
1776     GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1777
1778     //check if service queue contains a matching request
1779     requesting_session = find_matching_session (from_service_tail,
1780                                                 &session->key,
1781                                                 session->total,
1782                                                 &needed_state, NULL);
1783     if (NULL != requesting_session) {
1784       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));
1785       if (GNUNET_OK != compute_service_response (requesting_session, session))
1786         session->client_notification_task =
1787               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1788                                         session);
1789
1790     }
1791     else {
1792       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));
1793       // no matching session exists yet, store the response
1794       // for later processing by handle_service_request()
1795     }
1796   }
1797   GNUNET_SERVER_receive_done (client, GNUNET_YES);
1798 }
1799
1800
1801 /**
1802  * Function called for inbound tunnels.
1803  *
1804  * @param cls closure
1805  * @param tunnel new handle to the tunnel
1806  * @param initiator peer that started the tunnel
1807  * @param port unused
1808  * @return session associated with the tunnel
1809  */
1810 static void *
1811 tunnel_incoming_handler (void *cls,
1812                          struct GNUNET_MESH_Tunnel *tunnel,
1813                          const struct GNUNET_PeerIdentity *initiator,
1814                          uint32_t port)
1815 {
1816   struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1817
1818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("New incoming tunnel from peer %s.\n"), GNUNET_i2s (initiator));
1819   
1820   c->peer = *initiator;
1821   c->tunnel = tunnel;
1822   c->role = BOB;
1823   c->state = WAITING_FOR_SERVICE_REQUEST;
1824   return c;
1825 }
1826
1827
1828 /**
1829  * Function called whenever a tunnel is destroyed.  Should clean up
1830  * any associated state.
1831  *
1832  * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
1833  *
1834  * @param cls closure (set from GNUNET_MESH_connect)
1835  * @param tunnel connection to the other end (henceforth invalid)
1836  * @param tunnel_ctx place where local state associated
1837  *                   with the tunnel is stored
1838  */
1839 static void
1840 tunnel_destruction_handler (void *cls,
1841                             const struct GNUNET_MESH_Tunnel *tunnel,
1842                             void *tunnel_ctx)
1843 {
1844   struct ServiceSession * session = tunnel_ctx;
1845   struct ServiceSession * client_session;
1846   struct ServiceSession * curr;
1847
1848   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1849               _ ("Peer disconnected, terminating session %s with peer (%s)\n"),
1850               GNUNET_h2s (&session->key),
1851               GNUNET_i2s (&session->peer));
1852   if (ALICE == session->role) {
1853     // as we have only one peer connected in each session, just remove the session
1854
1855     if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown)) {
1856       session->tunnel = NULL;
1857       // if this happened before we received the answer, we must terminate the session
1858       session->client_notification_task =
1859               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1860                                         session);
1861     }
1862   }
1863   else { //(BOB == session->role) service session
1864     // remove the session, unless it has already been dequeued, but somehow still active
1865     // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1866     // scenario: disconnect before alice can send her message to bob.
1867     for (curr = from_service_head; NULL != curr; curr = curr->next)
1868       if (curr == session) {
1869         GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1870         break;
1871       }
1872     // there is a client waiting for this service session, terminate it, too!
1873     // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1874     client_session = find_matching_session (from_client_tail,
1875                                             &session->key,
1876                                             session->total,
1877                                             NULL, NULL);
1878     free_session_variables (session);
1879     GNUNET_free (session);
1880
1881     // the client has to check if it was waiting for a result
1882     // or if it was a responder, no point in adding more statefulness
1883     if (client_session && (!do_shutdown)) {
1884       client_session->state = FINALIZED;
1885       client_session->client_notification_task =
1886               GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1887                                         client_session);
1888     }
1889   }
1890 }
1891
1892
1893 /**
1894  * Compute our scalar product, done by Alice
1895  *
1896  * @param session - the session associated with this computation
1897  * @return product as MPI, never NULL
1898  */
1899 static gcry_mpi_t
1900 compute_scalar_product (struct ServiceSession * session)
1901 {
1902   uint32_t count;
1903   gcry_mpi_t t;
1904   gcry_mpi_t u;
1905   gcry_mpi_t u_prime;
1906   gcry_mpi_t p;
1907   gcry_mpi_t p_prime;
1908   gcry_mpi_t tmp;
1909   unsigned int i;
1910
1911   count = session->used;
1912   tmp = gcry_mpi_new (KEYBITS);
1913   // due to the introduced static offset S, we now also have to remove this
1914   // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1915   // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1916   for (i = 0; i < count; i++) {
1917     decrypt_element (session->r[i], session->r[i], my_mu, my_lambda, my_n, my_nsquare);
1918     gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1919     gcry_mpi_sub (session->r[i], session->r[i], my_offset);
1920     decrypt_element (session->r_prime[i], session->r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1921     gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1922     gcry_mpi_sub (session->r_prime[i], session->r_prime[i], my_offset);
1923   }
1924
1925   // calculate t = sum(ai)
1926   t = compute_square_sum (session->a, count);
1927
1928   // calculate U
1929   u = gcry_mpi_new (0);
1930   tmp = compute_square_sum (session->r, count);
1931   gcry_mpi_sub (u, u, tmp);
1932   gcry_mpi_release (tmp);
1933
1934   //calculate U'
1935   u_prime = gcry_mpi_new (0);
1936   tmp = compute_square_sum (session->r_prime, count);
1937   gcry_mpi_sub (u_prime, u_prime, tmp);
1938
1939   GNUNET_assert (p = gcry_mpi_new (0));
1940   GNUNET_assert (p_prime = gcry_mpi_new (0));
1941
1942   // compute P
1943   decrypt_element (session->s, session->s, my_mu, my_lambda, my_n, my_nsquare);
1944   decrypt_element (session->s_prime, session->s_prime, my_mu, my_lambda, my_n, my_nsquare);
1945
1946   // compute P
1947   gcry_mpi_add (p, session->s, t);
1948   gcry_mpi_add (p, p, u);
1949
1950   // compute P'
1951   gcry_mpi_add (p_prime, session->s_prime, t);
1952   gcry_mpi_add (p_prime, p_prime, u_prime);
1953
1954   gcry_mpi_release (t);
1955   gcry_mpi_release (u);
1956   gcry_mpi_release (u_prime);
1957
1958   // compute product
1959   gcry_mpi_sub (p, p, p_prime);
1960   gcry_mpi_release (p_prime);
1961   tmp = gcry_mpi_set_ui (tmp, 2);
1962   gcry_mpi_div (p, NULL, p, tmp, 0);
1963
1964   gcry_mpi_release (tmp);
1965   for (i = 0; i < count; i++)
1966     gcry_mpi_release (session->a[i]);
1967   GNUNET_free (session->a);
1968   session->a = NULL;
1969
1970   return p;
1971 }
1972
1973
1974 /**
1975  * Handle a multipart-chunk of a request from another service to calculate a scalarproduct with us.
1976  *
1977  * @param cls closure (set from #GNUNET_MESH_connect)
1978  * @param tunnel connection to the other end
1979  * @param tunnel_ctx place to store local state associated with the tunnel
1980  * @param message the actual message
1981  * @return #GNUNET_OK to keep the connection open,
1982  *         #GNUNET_SYSERR to close it (signal serious error)
1983  */
1984 static int
1985 handle_service_request_multipart (void *cls,
1986                                   struct GNUNET_MESH_Tunnel * tunnel,
1987                                   void **tunnel_ctx,
1988                                   const struct GNUNET_MessageHeader * message)
1989 {
1990   struct ServiceSession * session;
1991   const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
1992   uint32_t used_elements;
1993   uint32_t contained_elements = 0;
1994   uint32_t msg_length;
1995   unsigned char * current;
1996   gcry_error_t rc;
1997   int32_t i = -1;
1998
1999   // are we in the correct state?
2000   session = (struct ServiceSession *) * tunnel_ctx;
2001   if ((BOB != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2002     goto except;
2003   }
2004   // shorter than minimum?
2005   if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2006     goto except;
2007   }
2008   used_elements = session->used;
2009   contained_elements = ntohl (msg->multipart_element_count);
2010   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2011           +contained_elements * PAILLIER_ELEMENT_LENGTH;
2012   //sanity check
2013   if ((ntohs (msg->header.size) != msg_length)
2014       || (used_elements < contained_elements + session->transferred)) {
2015     goto except;
2016   }
2017   current = (unsigned char *) &msg[1];
2018   if (contained_elements != 0) {
2019     // Convert each vector element to MPI_value
2020     for (i = session->transferred; i < session->transferred + contained_elements; i++) {
2021       size_t read = 0;
2022       if (0 != (rc = gcry_mpi_scan (&session->a[i],
2023                                     GCRYMPI_FMT_USG,
2024                                     &current[i * PAILLIER_ELEMENT_LENGTH],
2025                                     PAILLIER_ELEMENT_LENGTH,
2026                                     &read))) {
2027         LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2028         goto except;
2029       }
2030     }
2031     session->transferred += contained_elements;
2032
2033     if (session->transferred == used_elements) {
2034       // single part finished
2035       session->state = SERVICE_REQUEST_RECEIVED;
2036       if (session->response) {
2037         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2038         if (GNUNET_OK != compute_service_response (session, session->response)) {
2039           //something went wrong, remove it again...
2040           goto except;
2041         }
2042       }
2043       else
2044         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2045     }
2046     else {
2047       // multipart message
2048     }
2049   }
2050
2051   return GNUNET_OK;
2052 except:
2053   // and notify our client-session that we could not complete the session
2054   GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2055   if (session->response)
2056     // we just found the responder session in this queue
2057     session->response->client_notification_task =
2058           GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2059                                     session->response);
2060   free_session_variables (session);
2061   GNUNET_free (session);
2062   return GNUNET_SYSERR;
2063 }
2064
2065
2066 /**
2067  * Handle a request from another service to calculate a scalarproduct with us.
2068  *
2069  * @param cls closure (set from #GNUNET_MESH_connect)
2070  * @param tunnel connection to the other end
2071  * @param tunnel_ctx place to store local state associated with the tunnel
2072  * @param message the actual message
2073  * @return #GNUNET_OK to keep the connection open,
2074  *         #GNUNET_SYSERR to close it (signal serious error)
2075  */
2076 static int
2077 handle_service_request (void *cls,
2078                         struct GNUNET_MESH_Tunnel * tunnel,
2079                         void **tunnel_ctx,
2080                         const struct GNUNET_MessageHeader * message)
2081 {
2082   struct ServiceSession * session;
2083   const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
2084   uint32_t mask_length;
2085   uint32_t pk_length;
2086   uint32_t used_elements;
2087   uint32_t contained_elements = 0;
2088   uint32_t element_count;
2089   uint32_t msg_length;
2090   unsigned char * current;
2091   gcry_error_t rc;
2092   int32_t i = -1;
2093   enum SessionState needed_state;
2094
2095   session = (struct ServiceSession *) * tunnel_ctx;
2096   if (WAITING_FOR_SERVICE_REQUEST != session->state) {
2097     goto invalid_msg;
2098   }
2099   // Check if message was sent by me, which would be bad!
2100   if (!memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity))) {
2101     GNUNET_free (session);
2102     GNUNET_break (0);
2103     return GNUNET_SYSERR;
2104   }
2105   // shorter than expected?
2106   if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request)) {
2107     GNUNET_free (session);
2108     GNUNET_break_op (0);
2109     return GNUNET_SYSERR;
2110   }
2111   mask_length = ntohl (msg->mask_length);
2112   pk_length = ntohl (msg->pk_length);
2113   used_elements = ntohl (msg->total_element_count);
2114   contained_elements = ntohl (msg->contained_element_count);
2115   element_count = ntohl (msg->element_count);
2116   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
2117           +mask_length + pk_length + contained_elements * PAILLIER_ELEMENT_LENGTH;
2118
2119   //sanity check: is the message as long as the message_count fields suggests?
2120   if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements) || (used_elements < contained_elements)
2121       || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
2122       ) {
2123     GNUNET_free (session);
2124     GNUNET_break_op (0);
2125     return GNUNET_SYSERR;
2126   }
2127   if (find_matching_session (from_service_tail,
2128                              &msg->key,
2129                              element_count,
2130                              NULL,
2131                              NULL)) {
2132     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
2133     GNUNET_free (session);
2134     return GNUNET_SYSERR;
2135   }
2136
2137   session->total = element_count;
2138   session->used = used_elements;
2139   session->transferred = contained_elements;
2140   session->tunnel = tunnel;
2141
2142   // session key
2143   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
2144   current = (unsigned char *) &msg[1];
2145   //preserve the mask, we will need that later on
2146   session->mask = GNUNET_malloc (mask_length);
2147   memcpy (session->mask, current, mask_length);
2148   //the public key
2149   current += mask_length;
2150
2151   //convert the publickey to sexp
2152   if (0 != (rc = gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))) {
2153     LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_sexp_new", rc);
2154     GNUNET_free (session->mask);
2155     GNUNET_free (session);
2156     return GNUNET_SYSERR;
2157   }
2158   current += pk_length;
2159   //check if service queue contains a matching request
2160   needed_state = CLIENT_RESPONSE_RECEIVED;
2161   session->response = find_matching_session (from_client_tail,
2162                                              &session->key,
2163                                              session->total,
2164                                              &needed_state, NULL);
2165
2166   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
2167   session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2168   GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
2169   if (contained_elements != 0) {
2170     // Convert each vector element to MPI_value
2171     for (i = 0; i < contained_elements; i++) {
2172       size_t read = 0;
2173       if (0 != (rc = gcry_mpi_scan (&session->a[i],
2174                                     GCRYMPI_FMT_USG,
2175                                     &current[i * PAILLIER_ELEMENT_LENGTH],
2176                                     PAILLIER_ELEMENT_LENGTH,
2177                                     &read))) {
2178         LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2179         goto invalid_msg;
2180       }
2181     }
2182     if (contained_elements == used_elements) {
2183       // single part finished
2184       session->state = SERVICE_REQUEST_RECEIVED;
2185       if (session->response) {
2186         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
2187         if (GNUNET_OK != compute_service_response (session, session->response)) {
2188           //something went wrong, remove it again...
2189           goto invalid_msg;
2190         }
2191       }
2192       else
2193         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
2194     }
2195     else {
2196       // multipart message
2197     }
2198   }
2199   return GNUNET_OK;
2200 invalid_msg:
2201   GNUNET_break_op (0);
2202   if ((NULL != session->next) || (NULL != session->prev) || (from_service_head == session))
2203     GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
2204   // and notify our client-session that we could not complete the session
2205   if (session->response)
2206     // we just found the responder session in this queue
2207     session->response->client_notification_task =
2208           GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
2209                                     session->response);
2210   free_session_variables (session);
2211   return GNUNET_SYSERR;
2212 }
2213
2214
2215 /**
2216  * Handle a multipart chunk of a response we got from another service we wanted to calculate a scalarproduct with.
2217  *
2218  * @param cls closure (set from #GNUNET_MESH_connect)
2219  * @param tunnel connection to the other end
2220  * @param tunnel_ctx place to store local state associated with the tunnel
2221  * @param message the actual message
2222  * @return #GNUNET_OK to keep the connection open,
2223  *         #GNUNET_SYSERR to close it (signal serious error)
2224  */
2225 static int
2226 handle_service_response_multipart (void *cls,
2227                                    struct GNUNET_MESH_Tunnel * tunnel,
2228                                    void **tunnel_ctx,
2229                                    const struct GNUNET_MessageHeader * message)
2230 {
2231   struct ServiceSession * session;
2232   const struct GNUNET_SCALARPRODUCT_multipart_message * msg = (const struct GNUNET_SCALARPRODUCT_multipart_message *) message;
2233   unsigned char * current;
2234   size_t read;
2235   size_t i;
2236   uint32_t contained = 0;
2237   size_t msg_size;
2238   int rc;
2239
2240   GNUNET_assert (NULL != message);
2241   // are we in the correct state?
2242   session = (struct ServiceSession *) * tunnel_ctx;
2243   if ((ALICE != session->role) || (WAITING_FOR_MULTIPART_TRANSMISSION != session->state)) {
2244     goto invalid_msg;
2245   }
2246   // shorter than minimum?
2247   if (ntohs (msg->header.size) <= sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)) {
2248     goto invalid_msg;
2249   }
2250   contained = ntohl (msg->multipart_element_count);
2251   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_multipart_message)
2252           + 2 * contained * PAILLIER_ELEMENT_LENGTH;
2253   //sanity check: is the message as long as the message_count fields suggests?
2254   if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2255     goto invalid_msg;
2256   }
2257   current = (unsigned char *) &msg[1];
2258   // Convert each k[][perm] to its MPI_value
2259   for (i = 0; i < contained; i++) {
2260     if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2261                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2262       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2263       goto invalid_msg;
2264     }
2265     current += PAILLIER_ELEMENT_LENGTH;
2266     if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2267                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2268       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2269       goto invalid_msg;
2270     }
2271     current += PAILLIER_ELEMENT_LENGTH;
2272   }
2273   session->transferred += contained;
2274   if (session->transferred != session->used)
2275     return GNUNET_OK;
2276   session->state = SERVICE_RESPONSE_RECEIVED;
2277   session->product = compute_scalar_product (session);
2278   return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2279
2280 invalid_msg:
2281   GNUNET_break_op (0);
2282   free_session_variables (session);
2283   session->state = FINALIZED;
2284   session->tunnel = NULL;
2285   // send message with product to client
2286   if (ALICE == session->role)
2287     session->client_notification_task =
2288           GNUNET_SCHEDULER_add_now (&prepare_client_response,
2289                                     session);
2290   // the tunnel has done its job, terminate our connection and the tunnel
2291   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2292   // just close the connection, as recommended by Christian
2293   return GNUNET_SYSERR;
2294 }
2295
2296
2297 /**
2298  * Handle a response we got from another service we wanted to calculate a scalarproduct with.
2299  *
2300  * @param cls closure (set from #GNUNET_MESH_connect)
2301  * @param tunnel connection to the other end
2302  * @param tunnel_ctx place to store local state associated with the tunnel
2303  * @param message the actual message
2304  * @return #GNUNET_OK to keep the connection open,
2305  *         #GNUNET_SYSERR to close it (we are done)
2306  */
2307 static int
2308 handle_service_response (void *cls,
2309                          struct GNUNET_MESH_Tunnel * tunnel,
2310                          void **tunnel_ctx,
2311                          const struct GNUNET_MessageHeader * message)
2312 {
2313   struct ServiceSession * session;
2314   const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
2315   unsigned char * current;
2316   size_t read;
2317   size_t i;
2318   uint32_t contained = 0;
2319   size_t msg_size;
2320   int rc;
2321
2322   GNUNET_assert (NULL != message);
2323   session = (struct ServiceSession *) * tunnel_ctx;
2324   // are we in the correct state?
2325   if (session->state != WAITING_FOR_SERVICE_REQUEST) {
2326     goto invalid_msg;
2327   }
2328   //we need at least a full message without elements attached
2329   msg_size = ntohs (msg->header.size);
2330   size_t expected = sizeof (struct GNUNET_SCALARPRODUCT_service_response) + 2 * PAILLIER_ELEMENT_LENGTH;
2331   
2332   if (expected > msg_size) {
2333     goto invalid_msg;
2334   }
2335   contained = ntohl (msg->contained_element_count);
2336   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
2337           + 2 * contained * PAILLIER_ELEMENT_LENGTH
2338           + 2 * PAILLIER_ELEMENT_LENGTH;
2339   //sanity check: is the message as long as the message_count fields suggests?
2340   if ((ntohs (msg->header.size) != msg_size) || (session->used < contained)) {
2341     goto invalid_msg;
2342   }
2343   session->state = WAITING_FOR_MULTIPART_TRANSMISSION;
2344   session->transferred = contained;
2345   //convert s
2346   current = (unsigned char *) &msg[1];
2347   if (0 != (rc = gcry_mpi_scan (&session->s, GCRYMPI_FMT_USG, current,
2348                                 PAILLIER_ELEMENT_LENGTH, &read))) {
2349     LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2350     goto invalid_msg;
2351   }
2352   current += PAILLIER_ELEMENT_LENGTH;
2353   //convert stick
2354   if (0 != (rc = gcry_mpi_scan (&session->s_prime, GCRYMPI_FMT_USG, current,
2355                                 PAILLIER_ELEMENT_LENGTH, &read))) {
2356     LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2357     goto invalid_msg;
2358   }
2359   current += PAILLIER_ELEMENT_LENGTH;
2360   session->r = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2361   session->r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used);
2362   // Convert each k[][perm] to its MPI_value
2363   for (i = 0; i < contained; i++) {
2364     if (0 != (rc = gcry_mpi_scan (&session->r[i], GCRYMPI_FMT_USG, current,
2365                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2366       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2367       goto invalid_msg;
2368     }
2369     current += PAILLIER_ELEMENT_LENGTH;
2370     if (0 != (rc = gcry_mpi_scan (&session->r_prime[i], GCRYMPI_FMT_USG, current,
2371                                   PAILLIER_ELEMENT_LENGTH, &read))) {
2372       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2373       goto invalid_msg;
2374     }
2375     current += PAILLIER_ELEMENT_LENGTH;
2376   }
2377   if (session->transferred != session->used)
2378     return GNUNET_OK; //wait for the other multipart chunks
2379
2380   session->state = SERVICE_RESPONSE_RECEIVED;
2381   session->product = compute_scalar_product (session);
2382   return GNUNET_SYSERR; // terminate the tunnel right away, we are done here!
2383
2384 invalid_msg:
2385   GNUNET_break_op (0);
2386   free_session_variables (session);
2387   session->state = FINALIZED;
2388   session->tunnel = NULL;
2389   // send message with product to client
2390   if (ALICE == session->role)
2391     session->client_notification_task =
2392           GNUNET_SCHEDULER_add_now (&prepare_client_response,
2393                                     session);
2394   // the tunnel has done its job, terminate our connection and the tunnel
2395   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2396   // just close the connection, as recommended by Christian
2397   return GNUNET_SYSERR;
2398 }
2399
2400
2401 /**
2402  * Task run during shutdown.
2403  *
2404  * @param cls unused
2405  * @param tc unused
2406  */
2407 static void
2408 shutdown_task (void *cls,
2409                const struct GNUNET_SCHEDULER_TaskContext *tc)
2410 {
2411   struct ServiceSession * session;
2412   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2413
2414   do_shutdown = GNUNET_YES;
2415
2416   // terminate all owned open tunnels.
2417   for (session = from_client_head; NULL != session; session = session->next) {
2418     if ((FINALIZED != session->state) && (NULL != session->tunnel)) {
2419       GNUNET_MESH_tunnel_destroy (session->tunnel);
2420       session->tunnel = NULL;
2421     }
2422     if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task) {
2423       GNUNET_SCHEDULER_cancel (session->client_notification_task);
2424       session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
2425     }
2426     if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task) {
2427       GNUNET_SCHEDULER_cancel (session->service_request_task);
2428       session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
2429     }
2430     if (NULL != session->client) {
2431       GNUNET_SERVER_client_disconnect (session->client);
2432       session->client = NULL;
2433     }
2434   }
2435   for (session = from_service_head; NULL != session; session = session->next)
2436     if (NULL != session->tunnel) {
2437       GNUNET_MESH_tunnel_destroy (session->tunnel);
2438       session->tunnel = NULL;
2439     }
2440
2441   if (my_mesh) {
2442     GNUNET_MESH_disconnect (my_mesh);
2443     my_mesh = NULL;
2444   }
2445 }
2446
2447
2448 /**
2449  * Initialization of the program and message handlers
2450  *
2451  * @param cls closure
2452  * @param server the initialized server
2453  * @param c configuration to use
2454  */
2455 static void
2456 run (void *cls,
2457      struct GNUNET_SERVER_Handle *server,
2458      const struct GNUNET_CONFIGURATION_Handle *c)
2459 {
2460   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2461     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2462     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2463     {NULL, NULL, 0, 0}
2464   };
2465   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2466     { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2467     { &handle_service_request_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB_MULTIPART, 0},
2468     { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2469     { &handle_service_response_multipart, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE_MULTIPART, 0},
2470     {NULL, 0, 0}
2471   };
2472   static const uint32_t ports[] = {
2473     GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2474     0
2475   };
2476   //generate private/public key set
2477   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2478   generate_keyset ();
2479   // register server callbacks and disconnect handler
2480   GNUNET_SERVER_add_handlers (server, server_handlers);
2481   GNUNET_SERVER_disconnect_notify (server,
2482                                    &handle_client_disconnect,
2483                                    NULL);
2484   GNUNET_break (GNUNET_OK ==
2485                 GNUNET_CRYPTO_get_peer_identity (c,
2486                                                  &me));
2487   my_mesh = GNUNET_MESH_connect (c, NULL,
2488                                  &tunnel_incoming_handler,
2489                                  &tunnel_destruction_handler,
2490                                  mesh_handlers, ports);
2491   if (!my_mesh) {
2492     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2493     GNUNET_SCHEDULER_shutdown ();
2494     return;
2495   }
2496   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2497   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2498                                 &shutdown_task,
2499                                 NULL);
2500 }
2501
2502
2503 /**
2504  * The main function for the scalarproduct service.
2505  *
2506  * @param argc number of arguments from the command line
2507  * @param argv command line arguments
2508  * @return 0 ok, 1 on error
2509  */
2510 int
2511 main (int argc, char *const *argv)
2512 {
2513   return (GNUNET_OK ==
2514           GNUNET_SERVICE_run (argc, argv,
2515                               "scalarproduct",
2516                               GNUNET_SERVICE_OPTION_NONE,
2517                               &run, NULL)) ? 0 : 1;
2518 }
2519
2520 /* end of gnunet-service-scalarproduct.c */