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