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