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