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