re-added collective disconnect command to the scalarproduct 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                                                  &request->peer, //must be specified, we are a slave/participant/non-owner
907                                                  msg_length,
908                                                  &do_send_message,
909                                                  msg_obj);
910       // we don't care if it could be send or not. either way, the session is over for us.
911       request->state = FINALIZED;
912       response->state = FINALIZED;
913     }
914   else
915     {
916       // TODO FEATURE: fallback to fragmentation, in case the message is too long
917       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!)\n"));
918     }
919
920   //disconnect our client
921   if ( ! request->service_transmit_handle)
922     {
923       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
924       GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, response);
925       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
926                                     &prepare_client_end_notification,
927                                     response);
928       return GNUNET_NO;
929     }
930   return GNUNET_OK;
931 }
932
933
934 /**
935  * executed by bob: 
936  * compute the values 
937  *  (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)})$
938  *  (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
939  *      S: $S := E_A(\sum (r_i + b_i)^2)$
940  *     S': $S' := E_A(\sum r_i^2)$
941  * 
942  * @param request the requesting session + bob's requesting peer
943  * @param response the responding session + bob's client handle
944  * @return GNUNET_SYSERR if the computation failed
945  *         GNUNET_OK if everything went well.
946  */
947 static int
948 compute_service_response (struct ServiceSession * request,
949                           struct ServiceSession * response)
950 {
951   int i;
952   int j;
953   int ret = GNUNET_SYSERR;
954   unsigned int * p;
955   unsigned int * q;
956   uint16_t count;
957   gcry_mpi_t * rand = NULL;
958   gcry_mpi_t * r = NULL;
959   gcry_mpi_t * r_prime = NULL;
960   gcry_mpi_t * b;
961   gcry_mpi_t * a_pi;
962   gcry_mpi_t * a_pi_prime;
963   gcry_mpi_t * b_pi;
964   gcry_mpi_t * rand_pi;
965   gcry_mpi_t * rand_pi_prime;
966   gcry_mpi_t s = NULL;
967   gcry_mpi_t s_prime = NULL;
968   gcry_mpi_t remote_n = NULL;
969   gcry_mpi_t remote_nsquare;
970   gcry_mpi_t remote_g = NULL;
971   gcry_sexp_t tmp_exp;
972   uint32_t value;
973
974   count = request->used_element_count;
975
976   b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
977   a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
978   b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
979   a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
980   rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
981   rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
982
983   // convert responder session to from long to mpi
984   for (i = 0, j = 0; i < response->element_count && j < count; i++)
985     {
986       if (request->mask[i / 8] & (1 << (i % 8)))
987         {
988           value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
989           // long to gcry_mpi_t
990           if (0 > response->vector[i])
991             {
992               b[j] = gcry_mpi_new (0);
993               gcry_mpi_sub_ui (b[j], b[j], value);
994             }
995           else
996             {
997               b[j] = gcry_mpi_set_ui (NULL, value);
998             }
999           j++;
1000         }
1001     }
1002   GNUNET_free (response->vector);
1003   response->vector = NULL;
1004
1005   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
1006   if ( ! tmp_exp)
1007     {
1008       GNUNET_break_op (0);
1009       gcry_sexp_release (request->remote_pubkey);
1010       request->remote_pubkey = NULL;
1011       goto except;
1012     }
1013   remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1014   if ( ! remote_n)
1015     {
1016       GNUNET_break (0);
1017       gcry_sexp_release (tmp_exp);
1018       goto except;
1019     }
1020   remote_nsquare = gcry_mpi_new (KEYBITS + 1);
1021   gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
1022   gcry_sexp_release (tmp_exp);
1023   tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
1024   gcry_sexp_release (request->remote_pubkey);
1025   request->remote_pubkey = NULL;
1026   if ( ! tmp_exp)
1027     {
1028       GNUNET_break_op (0);
1029       gcry_mpi_release (remote_n);
1030       goto except;
1031     }
1032   remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
1033   if ( ! remote_g)
1034     {
1035       GNUNET_break (0);
1036       gcry_mpi_release (remote_n);
1037       gcry_sexp_release (tmp_exp);
1038       goto except;
1039     }
1040   gcry_sexp_release (tmp_exp);
1041
1042   // generate r, p and q
1043   rand = generate_random_vector (count);
1044   p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1045   q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
1046   //initialize the result vectors
1047   r = initialize_mpi_vector (count);
1048   r_prime = initialize_mpi_vector (count);
1049
1050   // copy the REFERNCES of a, b and r into aq and bq. we will not change 
1051   // those values, thus we can work with the references
1052   memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
1053   memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
1054   memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
1055   memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
1056   memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
1057
1058   // generate p and q permutations for a, b and r
1059   GNUNET_assert (permute_vector (a_pi, p, count));
1060   GNUNET_assert (permute_vector (b_pi, p, count));
1061   GNUNET_assert (permute_vector (rand_pi, p, count));
1062   GNUNET_assert (permute_vector (a_pi_prime, q, count));
1063   GNUNET_assert (permute_vector (rand_pi_prime, q, count));
1064
1065   // encrypt the element
1066   // for the sake of readability I decided to have dedicated permutation
1067   // vectors, which get rid of all the lookups in p/q. 
1068   // however, ap/aq are not absolutely necessary but are just abstraction
1069   // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
1070   for (i = 0; i < count; i++)
1071     {
1072       // E(S - r_pi - b_pi)
1073       gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
1074       gcry_mpi_sub (r[i], r[i], b_pi[i]);
1075       encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
1076
1077       // E(S - r_pi - b_pi) * E(S + a_pi) ==  E(2*S + a - r - b)
1078       gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
1079     }
1080   GNUNET_free (a_pi);
1081   GNUNET_free (b_pi);
1082   GNUNET_free (rand_pi);
1083
1084   // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
1085   for (i = 0; i < count; i++)
1086     {
1087       // E(S - r_qi)
1088       gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
1089       encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
1090
1091       // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
1092       gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
1093     }
1094   GNUNET_free (a_pi_prime);
1095   GNUNET_free (rand_pi_prime);
1096
1097   // Calculate S' =  E(SUM( r_i^2 ))
1098   s_prime = compute_square_sum (rand, count);
1099   encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
1100
1101   // Calculate S = E(SUM( (r_i + b_i)^2 ))
1102   for (i = 0; i < count; i++)
1103     {
1104       gcry_mpi_add (rand[i], rand[i], b[i]);
1105     }
1106   s = compute_square_sum (rand, count);
1107   encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
1108   gcry_mpi_release (remote_n);
1109   gcry_mpi_release (remote_g);
1110   gcry_mpi_release (remote_nsquare);
1111
1112   // release r and tmp
1113   for (i = 0; i < count; i++)
1114     // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
1115     gcry_mpi_release (rand[i]);
1116
1117   // copy the Kp[], Kq[], S and Stick into a new message
1118   if (GNUNET_YES != prepare_service_response (r, r_prime, s, s_prime, request, response))
1119     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Failed to communicate with `%s', scalar product calculation aborted.\n"),
1120                 GNUNET_i2s (&request->peer));
1121   else
1122     ret = GNUNET_OK;
1123
1124   for (i = 0; i < count; i++)
1125     {
1126       gcry_mpi_release (r_prime[i]);
1127       gcry_mpi_release (r[i]);
1128     }
1129
1130   gcry_mpi_release (s);
1131   gcry_mpi_release (s_prime);
1132
1133 except:
1134   for (i = 0; i < count; i++)
1135     {
1136       gcry_mpi_release (b[i]);
1137       gcry_mpi_release (request->a[i]);
1138     }
1139
1140   GNUNET_free (b);
1141   GNUNET_free (request->a);
1142   request->a = NULL;
1143
1144   return ret;
1145 }
1146
1147
1148 /**
1149  * Executed by Alice, fills in a service-request message and sends it to the given peer
1150  * 
1151  * @param session the session associated with this request, then also holds the CORE-handle
1152  * @return #GNUNET_SYSERR if we could not send the message
1153  *         #GNUNET_NO if the message was too large
1154  *         #GNUNET_OK if we sent it
1155  */
1156 static void
1157 prepare_service_request (void *cls,
1158                          const struct GNUNET_PeerIdentity * peer,
1159                          const struct GNUNET_ATS_Information * atsi)
1160 {
1161   struct ServiceSession * session = cls;
1162   unsigned char * current;
1163   struct GNUNET_SCALARPRODUCT_service_request * msg;
1164   struct MessageObject * msg_obj;
1165   unsigned int i;
1166   unsigned int j;
1167   uint16_t msg_length;
1168   size_t element_length = 0; //gets initialized by gcry_mpi_print, but the compiler doesn't know that
1169   gcry_mpi_t a;
1170   uint32_t value;
1171
1172   GNUNET_assert (NULL != cls);
1173   GNUNET_assert (NULL != peer);
1174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (peer));
1175
1176   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1177           + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1178           + session->mask_length
1179           + my_pubkey_external_length;
1180
1181   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1182       + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1183       + session->mask_length
1184       + my_pubkey_external_length)
1185     {
1186       // TODO FEATURE: fallback to fragmentation, in case the message is too long
1187       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1188       GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1189       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1190                                     &prepare_client_end_notification,
1191                                     session);
1192       return;
1193     }
1194   msg = GNUNET_malloc (msg_length);
1195
1196   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1197   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1198   msg->mask_length = htons (session->mask_length);
1199   msg->pk_length = htons (my_pubkey_external_length);
1200   msg->used_element_count = htons (session->used_element_count);
1201   msg->element_count = htons (session->element_count);
1202   msg->header.size = htons (msg_length);
1203
1204   // fill in the payload
1205   current = (unsigned char *) &msg[1];
1206   // copy over the mask
1207   memcpy (current, session->mask, session->mask_length);
1208   // copy over our public key
1209   current += session->mask_length;
1210   memcpy (current, my_pubkey_external, my_pubkey_external_length);
1211   current += my_pubkey_external_length;
1212   
1213   // now copy over the element vector
1214   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1215   a = gcry_mpi_new (KEYBITS * 2);
1216   // encrypt our vector and generate string representations
1217   for (i = 0, j = 0; i < session->element_count; i++)
1218     {
1219       // if this is a used element...
1220       if (session->mask[i / 8] & 1 << (i % 8))
1221         {
1222           unsigned char * element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1223           value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1224
1225           a = gcry_mpi_set_ui (a, 0);
1226           // long to gcry_mpi_t
1227           if (session->vector[i] < 0)
1228             gcry_mpi_sub_ui (a, a, value);
1229           else
1230             gcry_mpi_add_ui (a, a, value);
1231
1232           session->a[j++] = gcry_mpi_set (NULL, a);
1233           gcry_mpi_add (a, a, my_offset);
1234           encrypt_element (a, a, my_g, my_n, my_nsquare);
1235
1236           // get representation as string
1237           // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1238           GNUNET_assert ( ! gcry_mpi_print (GCRYMPI_FMT_USG,
1239                                               element_exported, PAILLIER_ELEMENT_LENGTH,
1240                                               &element_length,
1241                                               a));
1242
1243           // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1244           adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1245
1246           // copy over to the message
1247           memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1248           current += PAILLIER_ELEMENT_LENGTH;
1249         }
1250     }
1251   gcry_mpi_release (a);
1252
1253   msg_obj = GNUNET_new (struct MessageObject);
1254   msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1255   msg_obj->transmit_handle = (void *) &session->service_transmit_handle; //and reset the transmit handle
1256   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting service request.\n"));
1257
1258   //transmit via mesh messaging
1259   session->state = WAITING_FOR_RESPONSE_FROM_SERVICE;
1260   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1261                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
1262                                                                         peer, //multicast to all targets, maybe useful in the future
1263                                                                         msg_length,
1264                                                                         &do_send_message,
1265                                                                         msg_obj);
1266   if ( ! session->service_transmit_handle)
1267     {
1268       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not send mutlicast message to tunnel!\n"));
1269       GNUNET_free (msg_obj);
1270       GNUNET_free (msg);
1271       GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1272       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1273                                     &prepare_client_end_notification,
1274                                     session);
1275     }
1276 }
1277
1278
1279 /**
1280  * Method called whenever a peer has disconnected from the tunnel.
1281  * Implementations of this callback must NOT call
1282  * #GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
1283  * to run in some other task later.  However, calling 
1284  * #GNUNET_MESH_notify_transmit_ready_cancel is allowed.
1285  *
1286  * @param cls closure
1287  * @param peer peer identity the tunnel stopped working with
1288  */
1289 static void
1290 tunnel_peer_disconnect_handler (void *cls, const struct GNUNET_PeerIdentity * peer)
1291 {
1292   // as we have only one peer connected in each session, just remove the session and say good bye
1293   struct ServiceSession * session = cls;
1294   struct ServiceSession * curr;
1295
1296   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1297               "Peer (%s) disconnected from our tunnel!\n",
1298               GNUNET_i2s (peer));
1299
1300   if ((session->role == ALICE) && (FINALIZED != session->state) && ( ! do_shutdown))
1301     {
1302       for (curr = from_client_head; NULL != curr; curr = curr->next)
1303         if (curr == session)
1304           {
1305             GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1306             break;
1307           }
1308       // FIXME: dangling tasks, code duplication, use-after-free, fun...
1309       GNUNET_SCHEDULER_add_now (&destroy_tunnel,
1310                                 session);
1311       // if this happened before we received the answer, we must terminate the session
1312       GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1313                                 session);
1314     }
1315 }
1316
1317
1318 /**
1319  * Handler for a client request message. 
1320  * Can either be type A or B
1321  *   A: request-initiation to compute a scalar product with a peer
1322  *   B: response role, keep the values + session and wait for a matching session or process a waiting request   
1323  *
1324  * @param cls closure
1325  * @param client identification of the client
1326  * @param message the actual message
1327  */
1328 static void
1329 handle_client_request (void *cls,
1330                        struct GNUNET_SERVER_Client *client,
1331                        const struct GNUNET_MessageHeader *message)
1332 {
1333   const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1334   struct ServiceSession * session;
1335   uint16_t element_count;
1336   uint16_t mask_length;
1337   uint16_t msg_type;
1338   int32_t * vector;
1339   uint32_t i;
1340
1341   GNUNET_assert (message);
1342
1343   //we need at least a peer and one message id to compare
1344   if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size))
1345     {
1346       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1347                   _ ("Too short message received from client!\n"));
1348       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1349       return;
1350     }
1351
1352   msg_type = ntohs (msg->header.type);
1353   element_count = ntohs (msg->element_count);
1354   mask_length = ntohs (msg->mask_length);
1355
1356   //sanity check: is the message as long as the message_count fields suggests?
1357   if (( ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_length))
1358       || (0 == element_count))
1359     {
1360       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1361                   _ ("Invalid message received from client, session information incorrect!\n"));
1362       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1363       return;
1364     }
1365
1366   // do we have a duplicate session here already?
1367   if (NULL != find_matching_session (from_client_tail,
1368                                      &msg->key,
1369                                      element_count,
1370                                      NULL, NULL))
1371     {
1372       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Duplicate session information received, cannot create new session with key `%s'\n"), GNUNET_h2s (&msg->key));
1373       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1374       return;
1375     }
1376
1377   session = GNUNET_new (struct ServiceSession);
1378   session->client = client;
1379   session->element_count = element_count;
1380   session->mask_length = mask_length;
1381   // get our transaction key
1382   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1383   //allocate memory for vector and encrypted vector
1384   session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1385   vector = (int32_t *) & msg[1];
1386
1387   if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type)
1388     {
1389       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), GNUNET_h2s (&session->key));
1390
1391       session->role = ALICE;
1392       // fill in the mask
1393       session->mask = GNUNET_malloc (mask_length);
1394       memcpy (session->mask, &vector[element_count], mask_length);
1395
1396       // copy over the elements
1397       session->used_element_count = 0;
1398       for (i = 0; i < element_count; i++)
1399         {
1400           session->vector[i] = ntohl (vector[i]);
1401           if (session->vector[i] == 0)
1402             session->mask[i / 8] &= ~(1 << (i % 8));
1403           if (session->mask[i / 8] & (1 << (i % 8)))
1404             session->used_element_count++;
1405         }
1406
1407       if ( ! session->used_element_count)
1408         {
1409           GNUNET_break_op (0);
1410           GNUNET_free (session->vector);
1411           GNUNET_free (session->a);
1412           GNUNET_free (session);
1413           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1414           return;
1415         }
1416       //session with ourself makes no sense!
1417       if ( ! memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1418         {
1419           GNUNET_break (0);
1420           GNUNET_free (session->vector);
1421           GNUNET_free (session->a);
1422           GNUNET_free (session);
1423           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1424           return;
1425         }
1426       // get our peer ID
1427       memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1428       GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Creating new tunnel to for session with key %s.\n"), GNUNET_h2s (&session->key));
1429       GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1430       session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1431                                                    prepare_service_request,
1432                                                    tunnel_peer_disconnect_handler,
1433                                                    session);
1434       if ( ! session->tunnel)
1435         {
1436           GNUNET_break (0);
1437           GNUNET_free (session->vector);
1438           GNUNET_free (session->a);
1439           GNUNET_free (session);
1440           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1441           return;
1442         }
1443       GNUNET_MESH_peer_request_connect_add (session->tunnel, &session->peer);
1444       GNUNET_SERVER_receive_done (client, GNUNET_YES);
1445       session->state = WAITING_FOR_BOBS_CONNECT;
1446     }
1447   else
1448     {
1449       struct ServiceSession * requesting_session;
1450       enum SessionState needed_state = REQUEST_FROM_SERVICE_RECEIVED;
1451
1452       session->role = BOB;
1453       session->mask = NULL;
1454       // copy over the elements
1455       session->used_element_count = element_count;
1456       for (i = 0; i < element_count; i++)
1457         session->vector[i] = ntohl (vector[i]);
1458       session->state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1459       
1460       GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1461       GNUNET_SERVER_receive_done (client, GNUNET_YES);
1462       //check if service queue contains a matching request 
1463       requesting_session = find_matching_session (from_service_tail,
1464                                                   &session->key,
1465                                                   session->element_count,
1466                                                   &needed_state, NULL);
1467       if (NULL != requesting_session)
1468         {
1469           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));
1470           if (GNUNET_OK != compute_service_response (requesting_session, session))
1471             {
1472               GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1473               GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1474                                             &prepare_client_end_notification,
1475                                             session);
1476             }
1477         }
1478       else
1479         GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s but NO matching service-request-session set, queuing element for later use.\n"), GNUNET_h2s (&session->key));
1480         // no matching session exists yet, store the response
1481         // for later processing by handle_service_request()
1482     }
1483 }
1484
1485
1486 /**
1487  * Function called for inbound tunnels. 
1488  *
1489  * @param cls closure
1490  * @param tunnel new handle to the tunnel
1491  * @param initiator peer that started the tunnel
1492  * @param atsi performance information for the tunnel
1493  * @return initial tunnel context for the tunnel
1494  *         (can be NULL -- that's not an error)
1495  */
1496 static void *
1497 tunnel_incoming_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
1498                          const struct GNUNET_PeerIdentity *initiator,
1499                          const struct GNUNET_ATS_Information *atsi)
1500 {
1501
1502   struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1503
1504   memcpy (&c->peer, initiator, sizeof (struct GNUNET_PeerIdentity));
1505   c->tunnel = tunnel;
1506   c->role = BOB;
1507   return c;
1508 }
1509
1510
1511 /**
1512  * Function called whenever an inbound tunnel is destroyed.  Should clean up
1513  * any associated state.
1514  *
1515  * @param cls closure (set from #GNUNET_MESH_connect)
1516  * @param tunnel connection to the other end (henceforth invalid)
1517  * @param tunnel_ctx place where local state associated
1518  *                   with the tunnel is stored (our 'struct TunnelState')
1519  */
1520 static void
1521 tunnel_destruction_handler (void *cls,
1522                             const struct GNUNET_MESH_Tunnel *tunnel,
1523                             void *tunnel_ctx)
1524 {
1525   struct ServiceSession * service_session = tunnel_ctx;
1526   struct ServiceSession * client_session;
1527   struct ServiceSession * curr;
1528
1529   GNUNET_assert (service_session);
1530   if (!memcmp (&service_session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1531     return;
1532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Tunnel destroyed, terminating session with peer (%s)\n"), GNUNET_i2s (&service_session->peer));
1533   // remove the session, unless it has already been dequeued, but somehow still active
1534   // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1535   for (curr = from_service_head; NULL != curr; curr = curr->next)
1536         if (curr == service_session)
1537           {
1538             GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1539             break;
1540           }
1541   // there is a client waiting for this service session, terminate it, too!
1542   // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1543   client_session = find_matching_session (from_client_tail,
1544                                           &service_session->key,
1545                                           service_session->element_count,
1546                                           NULL, NULL);
1547   free_session (service_session);
1548
1549   // the client has to check if it was waiting for a result 
1550   // or if it was a responder, no point in adding more statefulness
1551   if (client_session && ( ! do_shutdown))
1552     {
1553       // remove the session, we just found it in the queue, so it must be there
1554       GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, client_session);
1555       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1556                                     &prepare_client_end_notification,
1557                                     client_session);
1558     }
1559 }
1560
1561
1562 /**
1563  * Compute our scalar product, done by Alice
1564  * 
1565  * @param session - the session associated with this computation
1566  * @param kp - (1) from the protocol definition: 
1567  *             $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)})$
1568  * @param kq - (2) from the protocol definition: 
1569  *             $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
1570  * @param s - S from the protocol definition: 
1571  *            $S := E_A(\sum (r_i + b_i)^2)$
1572  * @param stick - S' from the protocol definition: 
1573  *                $S' := E_A(\sum r_i^2)$
1574  * @return product as MPI, never NULL
1575  */
1576 static gcry_mpi_t
1577 compute_scalar_product (struct ServiceSession * session,
1578                         gcry_mpi_t * r, gcry_mpi_t * r_prime, gcry_mpi_t s, gcry_mpi_t s_prime)
1579 {
1580   uint16_t count;
1581   gcry_mpi_t t;
1582   gcry_mpi_t u;
1583   gcry_mpi_t utick;
1584   gcry_mpi_t p;
1585   gcry_mpi_t ptick;
1586   gcry_mpi_t tmp;
1587   unsigned int i;
1588
1589   count = session->used_element_count;
1590   tmp = gcry_mpi_new (KEYBITS);
1591   // due to the introduced static offset S, we now also have to remove this
1592   // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
1593   // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
1594   for (i = 0; i < count; i++)
1595     {
1596       decrypt_element (r[i], r[i], my_mu, my_lambda, my_n, my_nsquare);
1597       gcry_mpi_sub(r[i],r[i],my_offset);
1598       gcry_mpi_sub(r[i],r[i],my_offset);
1599       decrypt_element (r_prime[i], r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
1600       gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
1601       gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
1602     }
1603
1604   // calculate t = sum(ai)
1605   t = compute_square_sum (session->a, count);
1606
1607   // calculate U
1608   u = gcry_mpi_new (0);
1609   tmp = compute_square_sum (r, count);
1610   gcry_mpi_sub (u, u, tmp);
1611   gcry_mpi_release (tmp);
1612
1613   //calculate U'
1614   utick = gcry_mpi_new (0);
1615   tmp = compute_square_sum (r_prime, count);
1616   gcry_mpi_sub (utick, utick, tmp);
1617
1618   GNUNET_assert (p = gcry_mpi_new (0));
1619   GNUNET_assert (ptick = gcry_mpi_new (0));
1620
1621   // compute P
1622   decrypt_element (s, s, my_mu, my_lambda, my_n, my_nsquare);
1623   decrypt_element (s_prime, s_prime, my_mu, my_lambda, my_n, my_nsquare);
1624   
1625   // compute P
1626   gcry_mpi_add (p, s, t);
1627   gcry_mpi_add (p, p, u);
1628
1629   // compute P'
1630   gcry_mpi_add (ptick, s_prime, t);
1631   gcry_mpi_add (ptick, ptick, utick);
1632
1633   gcry_mpi_release (t);
1634   gcry_mpi_release (u);
1635   gcry_mpi_release (utick);
1636
1637   // compute product
1638   gcry_mpi_sub (p, p, ptick);
1639   gcry_mpi_release (ptick);
1640   tmp = gcry_mpi_set_ui (tmp, 2);
1641   gcry_mpi_div (p, NULL, p, tmp, 0);
1642
1643   gcry_mpi_release (tmp);
1644   for (i = 0; i < count; i++)
1645     gcry_mpi_release (session->a[i]);
1646   GNUNET_free (session->a);
1647   session->a = NULL;
1648   
1649   return p;
1650 }
1651
1652
1653 /**
1654  * prepare the response we will send to alice or bobs' clients.
1655  * in Bobs case the product will be NULL. 
1656  * 
1657  * @param session  the session associated with our client.
1658  */
1659 static void
1660 prepare_client_response (void *cls,
1661                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1662 {
1663   struct ServiceSession * session = cls;
1664   struct GNUNET_SCALARPRODUCT_client_response * msg;
1665   unsigned char * product_exported = NULL;
1666   size_t product_length = 0;
1667   uint16_t msg_length = 0;
1668   struct MessageObject * msg_obj;
1669   int8_t range = 0;
1670   int sign;
1671
1672   if (session->product)
1673     {
1674       gcry_mpi_t value = gcry_mpi_new(0);
1675       
1676       sign = gcry_mpi_cmp_ui(session->product, 0);
1677       // libgcrypt can not handle a print of a negative number
1678       if (0 > sign){
1679           range = -1;
1680           gcry_mpi_sub(value, value, session->product);
1681       }
1682       else if(0 < sign){
1683           range = 1;
1684           gcry_mpi_add(value, value, session->product);
1685       }
1686       
1687       // get representation as string
1688       // unfortunately libgcrypt is too stupid to implement print-support in
1689       // signed GCRYMPI_FMT_STD format, and simply asserts in that case.
1690       // here is the associated sourcecode:
1691       // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
1692       if (range)
1693           GNUNET_assert ( ! gcry_mpi_aprint (GCRYMPI_FMT_USG, // FIXME: just log (& survive!)
1694                                              &product_exported,
1695                                              &product_length,
1696                                              session->product));
1697       
1698       gcry_mpi_release (session->product);
1699       session->product = NULL;
1700     }
1701
1702   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) + product_length;
1703   msg = GNUNET_malloc (msg_length);
1704   memcpy (&msg[1], product_exported, product_length);
1705   GNUNET_free_non_null (product_exported);
1706   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1707   msg->header.size = htons (msg_length);
1708   msg->range = range;
1709   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1710   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1711   msg->product_length = htonl (product_length);
1712   
1713   msg_obj = GNUNET_new (struct MessageObject);
1714   msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1715   msg_obj->transmit_handle = NULL; // don't reset the transmit handle
1716
1717   //transmit this message to our client
1718   session->client_transmit_handle =  // FIXME: use after free possibility during shutdown
1719           GNUNET_SERVER_notify_transmit_ready (session->client,
1720                                                msg_length,
1721                                                GNUNET_TIME_UNIT_FOREVER_REL,
1722                                                &do_send_message,
1723                                                msg_obj);
1724   if ( ! session->client_transmit_handle)
1725     {
1726       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);
1727       session->client = NULL;
1728       // callback was not called!
1729       GNUNET_free (msg_obj);
1730       GNUNET_free (msg);
1731     }
1732   else
1733       // gracefully sent message, just terminate session structure
1734       GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sent result to client (%p), this session (%s) has ended!\n"), session->client, GNUNET_h2s (&session->key));
1735   free_session (session);
1736 }
1737
1738
1739 /**
1740  * Handle a request from another service to calculate a scalarproduct with us.
1741  *
1742  * @param cls closure (set from #GNUNET_MESH_connect)
1743  * @param tunnel connection to the other end
1744  * @param tunnel_ctx place to store local state associated with the tunnel
1745  * @param sender who sent the message
1746  * @param message the actual message
1747  * @param atsi performance data for the connection
1748  * @return #GNUNET_OK to keep the connection open,
1749  *         #GNUNET_SYSERR to close it (signal serious error)
1750  */
1751 static int
1752 handle_service_request (void *cls,
1753                         struct GNUNET_MESH_Tunnel * tunnel,
1754                         void **tunnel_ctx,
1755                         const struct GNUNET_PeerIdentity * sender,
1756                         const struct GNUNET_MessageHeader * message,
1757                         const struct GNUNET_ATS_Information * atsi)
1758 {
1759   struct ServiceSession * session;
1760   const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
1761   uint16_t mask_length;
1762   uint16_t pk_length;
1763   uint16_t used_elements;
1764   uint16_t element_count;
1765   uint16_t msg_length;
1766   unsigned char * current;
1767   struct ServiceSession * responder_session;
1768   int32_t i = -1;
1769   enum SessionState needed_state;
1770
1771   session = (struct ServiceSession *) * tunnel_ctx;
1772   // is this tunnel already in use?
1773   if ( (session->next) || (from_service_head == session))
1774     {
1775       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Got a service request over a tunnel that is already in use, ignoring!\n"));
1776       return GNUNET_SYSERR;
1777     }
1778   // Check if message was sent by me, which would be bad!
1779   if ( ! memcmp (sender, &me, sizeof (struct GNUNET_PeerIdentity)))
1780     {
1781       GNUNET_break (0);
1782       GNUNET_free (session);
1783       return GNUNET_SYSERR;
1784     }
1785   // this protocol can at best be 1:N, but never M:N!
1786   // Check if the sender is not the peer, I am connected to, which would be bad!
1787   if (memcmp (sender, &session->peer, sizeof (struct GNUNET_PeerIdentity)))
1788     {
1789       GNUNET_break (0);
1790       GNUNET_free (session);
1791       return GNUNET_SYSERR;
1792     }
1793
1794   //we need at least a peer and one message id to compare
1795   if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request))
1796     {
1797       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
1798       GNUNET_free (session);
1799       return GNUNET_SYSERR;
1800     }
1801   mask_length = ntohs (msg->mask_length);
1802   pk_length = ntohs (msg->pk_length);
1803   used_elements = ntohs (msg->used_element_count);
1804   element_count = ntohs (msg->element_count);
1805   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1806                + mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
1807
1808   //sanity check: is the message as long as the message_count fields suggests?
1809   if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements)
1810       || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
1811       )
1812     {
1813       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer, message count does not match message length!\n"));
1814       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)));
1815       GNUNET_free (session);
1816       return GNUNET_SYSERR;
1817     }
1818   if (find_matching_session (from_service_tail,
1819                              &msg->key,
1820                              element_count,
1821                              NULL,
1822                              sender))
1823     {
1824       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
1825       GNUNET_free (session);
1826       return GNUNET_SYSERR;
1827     }
1828   
1829   memcpy (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity));
1830   session->state = REQUEST_FROM_SERVICE_RECEIVED;
1831   session->element_count = ntohs (msg->element_count);
1832   session->used_element_count = used_elements;
1833   session->tunnel = tunnel;
1834
1835   // session key
1836   memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1837   current = (unsigned char *) &msg[1];
1838   //preserve the mask, we will need that later on
1839   session->mask = GNUNET_malloc (mask_length);
1840   memcpy (session->mask, current, mask_length);
1841   //the public key
1842   current += mask_length;
1843
1844   //convert the publickey to sexp
1845   if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))
1846     {
1847       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
1848       GNUNET_free (session->mask);
1849       GNUNET_free (session);
1850       return GNUNET_SYSERR;
1851     }
1852
1853   current += pk_length;
1854
1855   //check if service queue contains a matching request 
1856   needed_state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1857   responder_session = find_matching_session (from_client_tail,
1858                                              &session->key,
1859                                              session->element_count,
1860                                              &needed_state, NULL);
1861
1862   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1863
1864   if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1865       +pk_length
1866       + mask_length
1867       + used_elements * PAILLIER_ELEMENT_LENGTH)
1868     {
1869       gcry_error_t ret = 0;
1870       session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1871       // Convert each vector element to MPI_value
1872       for (i = 0; i < used_elements; i++)
1873         {
1874           size_t read = 0;
1875
1876           ret = gcry_mpi_scan (&session->a[i],
1877                                GCRYMPI_FMT_USG,
1878                                &current[i * PAILLIER_ELEMENT_LENGTH],
1879                                PAILLIER_ELEMENT_LENGTH,
1880                                &read);
1881           if (ret)
1882             {
1883               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1884                           i, gcry_strsource (ret), gcry_strerror (ret));
1885               goto except;
1886             }
1887         }
1888       GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
1889       if (responder_session)
1890         {
1891           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1892           if (GNUNET_OK != compute_service_response (session, responder_session))
1893             {
1894               //something went wrong, remove it again...
1895               GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1896               goto except;
1897             }
1898         }
1899       else
1900           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1901       return GNUNET_OK;
1902     }
1903   else
1904     {
1905       // TODO FEATURE: fallback to fragmentation, in case the message is too long
1906       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1907       goto except;
1908     }
1909 except:
1910   for (i = 0; i < used_elements; i++)
1911     if (session->a[i])
1912       gcry_mpi_release (session->a[i]);
1913   gcry_sexp_release (session->remote_pubkey);
1914   session->remote_pubkey = NULL;
1915   GNUNET_free_non_null (session->a);
1916   session->a = NULL;
1917   free_session (session);
1918   // and notify our client-session that we could not complete the session
1919   if (responder_session)
1920     {
1921       // we just found the responder session in this queue
1922       GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, responder_session);
1923       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1924                                     &prepare_client_end_notification,
1925                                     responder_session);
1926     }
1927   return GNUNET_SYSERR;
1928 }
1929
1930
1931 /**
1932  * Handle a response we got from another service we wanted to calculate a scalarproduct with.
1933  *
1934  * @param cls closure (set from #GNUNET_MESH_connect)
1935  * @param tunnel connection to the other end
1936  * @param tunnel_ctx place to store local state associated with the tunnel
1937  * @param sender who sent the message
1938  * @param message the actual message
1939  * @param atsi performance data for the connection
1940  * @return #GNUNET_OK to keep the connection open,
1941  *         #GNUNET_SYSERR to close it (signal serious error)
1942  */
1943 static int
1944 handle_service_response (void *cls,
1945                          struct GNUNET_MESH_Tunnel * tunnel,
1946                          void **tunnel_ctx,
1947                          const struct GNUNET_PeerIdentity * sender,
1948                          const struct GNUNET_MessageHeader * message,
1949                          const struct GNUNET_ATS_Information * atsi)
1950 {
1951
1952   struct ServiceSession * session;
1953   struct GNUNET_SCALARPRODUCT_service_response * msg = (struct GNUNET_SCALARPRODUCT_service_response *) message;
1954   unsigned char * current;
1955   uint16_t count;
1956   gcry_mpi_t s = NULL;
1957   gcry_mpi_t s_prime = NULL;
1958   size_t read;
1959   size_t i;
1960   uint16_t used_element_count;
1961   size_t msg_size;
1962   gcry_mpi_t * r = NULL;
1963   gcry_mpi_t * r_prime = NULL;
1964   int rc;
1965
1966   GNUNET_assert (NULL != message);
1967   GNUNET_assert (NULL != sender);
1968   GNUNET_assert (NULL != tunnel_ctx);
1969   session = (struct ServiceSession *) * tunnel_ctx;
1970   GNUNET_assert (NULL != session);
1971   count = session->used_element_count;
1972   session->product = NULL;
1973
1974   if (memcmp (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity)))
1975     {
1976       GNUNET_break_op (0);
1977       goto invalid_msg;
1978     }
1979   //we need at least a peer and one message id to compare
1980   if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size))
1981     {
1982       GNUNET_break_op (0);
1983       goto invalid_msg;
1984     }
1985   used_element_count = ntohs (msg->used_element_count);
1986   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
1987           + 2 * used_element_count * PAILLIER_ELEMENT_LENGTH
1988           + 2 * PAILLIER_ELEMENT_LENGTH;
1989   //sanity check: is the message as long as the message_count fields suggests?
1990   if ((ntohs (msg->header.size) != msg_size) || (count != used_element_count))
1991     {
1992       GNUNET_break_op (0);
1993       goto invalid_msg;
1994     }
1995
1996   //convert s
1997   current = (unsigned char *) &msg[1];
1998   if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current, 
1999                      PAILLIER_ELEMENT_LENGTH, &read)))
2000     {
2001       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2002       GNUNET_break_op (0);
2003       goto invalid_msg;
2004     }
2005   current += PAILLIER_ELEMENT_LENGTH;
2006   //convert stick
2007   if (0 != (rc = gcry_mpi_scan (&s_prime, GCRYMPI_FMT_USG, current,
2008                        PAILLIER_ELEMENT_LENGTH, &read)))
2009     {
2010       LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2011       GNUNET_break_op (0);
2012       goto invalid_msg;
2013     }
2014   current += PAILLIER_ELEMENT_LENGTH;
2015
2016   r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2017   // Convert each kp[] to its MPI_value
2018   for (i = 0; i < count; i++)
2019     {
2020       if (0 != (rc = gcry_mpi_scan (&r[i], GCRYMPI_FMT_USG, current,
2021                            PAILLIER_ELEMENT_LENGTH, &read)))
2022         {
2023           LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2024       GNUNET_break_op (0);
2025           goto invalid_msg;
2026         }
2027       current += PAILLIER_ELEMENT_LENGTH;
2028     }
2029
2030
2031   r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
2032   // Convert each kq[] to its MPI_value
2033   for (i = 0; i < count; i++)
2034     {
2035       if (0 != (rc = gcry_mpi_scan (&r_prime[i], GCRYMPI_FMT_USG, current,
2036                            PAILLIER_ELEMENT_LENGTH, &read)))
2037         {
2038           LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
2039       GNUNET_break_op (0);
2040           goto invalid_msg;
2041         }
2042       current += PAILLIER_ELEMENT_LENGTH;
2043     }
2044   
2045   session->product = compute_scalar_product (session, r, r_prime, s, s_prime);
2046   
2047 invalid_msg:
2048   if (s)
2049     gcry_mpi_release (s);
2050   if (s_prime)
2051     gcry_mpi_release (s_prime);
2052   for (i = 0; r && i < count; i++)
2053     if (r[i]) gcry_mpi_release (r[i]);
2054   for (i = 0; r_prime && i < count; i++)
2055     if (r_prime[i]) gcry_mpi_release (r_prime[i]);
2056   GNUNET_free_non_null (r);
2057   GNUNET_free_non_null (r_prime);
2058   
2059   session->state = FINALIZED;
2060   // the tunnel has done its job, terminate our connection and the tunnel
2061   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
2062   GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
2063   GNUNET_SCHEDULER_add_now (&destroy_tunnel, session); // FIXME: use after free!
2064   // send message with product to client
2065   /* session->current_task = */ GNUNET_SCHEDULER_add_now (&prepare_client_response, session); // FIXME: dangling task!
2066   return GNUNET_OK;
2067   // if success: terminate the session gracefully, else terminate with error
2068 }
2069
2070
2071 /**
2072  * Task run during shutdown.
2073  *
2074  * @param cls unused
2075  * @param tc unused
2076  */
2077 static void
2078 shutdown_task (void *cls,
2079                const struct GNUNET_SCHEDULER_TaskContext *tc)
2080 {
2081   struct ServiceSession * curr;
2082   struct ServiceSession * next;
2083   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
2084
2085   do_shutdown = GNUNET_YES;
2086   // terminate all owned open tunnels.
2087   for (curr = from_client_head; NULL != curr; curr = next)
2088     {
2089       next = curr->next;
2090       if (FINALIZED != curr->state)
2091         {
2092           destroy_tunnel (curr, NULL);
2093           curr->state = FINALIZED;
2094         }
2095     }
2096   if (my_mesh)
2097     {
2098       GNUNET_MESH_disconnect (my_mesh);
2099       my_mesh = NULL;
2100     }
2101 }
2102
2103
2104 /**
2105  * Initialization of the program and message handlers
2106  *
2107  * @param cls closure
2108  * @param server the initialized server
2109  * @param c configuration to use
2110  */
2111 static void
2112 run (void *cls,
2113      struct GNUNET_SERVER_Handle *server,
2114      const struct GNUNET_CONFIGURATION_Handle *c)
2115 {
2116   static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2117     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
2118     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
2119     {NULL, NULL, 0, 0}
2120   };
2121   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2122     { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
2123     { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
2124     {NULL, 0, 0}
2125   };
2126   static GNUNET_MESH_ApplicationType mesh_types[] = {
2127     GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
2128     GNUNET_APPLICATION_TYPE_END
2129   };
2130
2131   //generate private/public key set
2132   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
2133   generate_keyset ();
2134   // register server callbacks and disconnect handler
2135   GNUNET_SERVER_add_handlers (server, server_handlers);
2136   GNUNET_SERVER_disconnect_notify (server,
2137                                    &handle_client_disconnect,
2138                                    NULL);
2139   GNUNET_break (GNUNET_OK ==
2140                 GNUNET_CRYPTO_get_host_identity (c,
2141                                                  &me));
2142   my_mesh = GNUNET_MESH_connect (c, NULL,
2143                                  &tunnel_incoming_handler,
2144                                  &tunnel_destruction_handler,
2145                                  mesh_handlers, mesh_types);
2146   if (!my_mesh)
2147     {
2148       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2149       GNUNET_SCHEDULER_shutdown ();
2150       return;
2151     }
2152   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2153   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2154                                 &shutdown_task,
2155                                 NULL);
2156 }
2157
2158
2159 /**
2160  * The main function for the scalarproduct service.
2161  *
2162  * @param argc number of arguments from the command line
2163  * @param argv command line arguments
2164  * @return 0 ok, 1 on error
2165  */
2166 int
2167 main (int argc, char *const *argv)
2168 {
2169   return (GNUNET_OK ==
2170           GNUNET_SERVICE_run (argc, argv,
2171                               "scalarproduct",
2172                               GNUNET_SERVICE_OPTION_NONE,
2173                               &run, NULL)) ? 0 : 1;
2174 }
2175
2176 /* end of gnunet-service-ext.c */