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