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