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