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