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