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