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