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