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