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