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