allocate r and r_prime MPIs before use
[oweals/gnunet.git] / src / scalarproduct / gnunet-scalarproduct.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013, 2014 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-scalarproduct.c
23  * @brief scalarproduct client
24  * @author Christian M. Fuchs
25  */
26 #define GCRYPT_NO_DEPRECATED
27 #include <gcrypt.h>
28 #include <inttypes.h>
29
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_scalarproduct_service.h"
33 #include "gnunet_protocols.h"
34 #include "scalarproduct.h"
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "gnunet-scalarproduct",__VA_ARGS__)
37
38
39 /**
40  * the session key identifying this computation
41  */
42 static struct GNUNET_HashCode session_key;
43
44 /**
45  * PeerID we want to compute a scalar product with
46  */
47 static struct GNUNET_PeerIdentity peer_id;
48
49 /**
50  * Option -p: destination peer identity for checking message-ids with
51  */
52 static char *input_peer_id;
53
54 /**
55  * Option -p: destination peer identity for checking message-ids with
56  */
57 static char *input_session_key;
58
59 /**
60  * Option -e: vector to calculate a scalarproduct with
61  */
62 static char *input_elements;
63
64 /**
65  * Global return value
66  */
67 static int ret = -1;
68
69 /**
70  * our Scalarproduct Computation handle
71  */
72 static struct GNUNET_SCALARPRODUCT_ComputationHandle *computation;
73
74
75 /**
76  * Callback called if we are initiating a new computation session
77  *
78  * @param cls unused
79  * @param status if our job was successfully processed
80  */
81 static void
82 responder_callback (void *cls,
83                     enum GNUNET_SCALARPRODUCT_ResponseStatus status)
84 {
85   switch (status)
86   {
87   case GNUNET_SCALARPRODUCT_Status_Success:
88     ret = 0;
89     LOG (GNUNET_ERROR_TYPE_INFO,
90          "Session %s concluded.\n",
91          GNUNET_h2s (&session_key));
92     break;
93   case GNUNET_SCALARPRODUCT_Status_InvalidResponse:
94     LOG (GNUNET_ERROR_TYPE_ERROR,
95          "Session %s failed: invalid response\n",
96          GNUNET_h2s (&session_key));
97     break;
98   case GNUNET_SCALARPRODUCT_Status_Failure:
99     LOG (GNUNET_ERROR_TYPE_ERROR,
100          "Session %s failed: service failure\n",
101          GNUNET_h2s (&session_key));
102     break;
103   case GNUNET_SCALARPRODUCT_Status_ServiceDisconnected:
104     LOG (GNUNET_ERROR_TYPE_ERROR,
105          "Session %s failed: service disconnect!\n",
106          GNUNET_h2s (&session_key));
107     break;
108   default:
109     LOG (GNUNET_ERROR_TYPE_ERROR,
110          "Session %s failed: return code %d\n",
111          GNUNET_h2s (&session_key),
112          status);
113   }
114   computation = NULL;
115   GNUNET_SCHEDULER_shutdown ();
116 }
117
118
119 /**
120  * Callback called if we are initiating a new computation session
121  *
122  * @param cls unused
123  * @param status if our job was successfully processed
124  * @param result the result in gnu/gcry MPI format
125  */
126 static void
127 requester_callback (void *cls,
128                     enum GNUNET_SCALARPRODUCT_ResponseStatus status,
129                     gcry_mpi_t result)
130 {
131   unsigned char *buf;
132   gcry_error_t rc;
133
134   switch (status)
135   {
136   case GNUNET_SCALARPRODUCT_Status_Success:
137     if (0 == (rc = gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buf, NULL, result)))
138     {
139       ret = 0;
140       printf ("%s", buf);
141     }
142     else
143       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR,
144                 "gcry_mpi_aprint",
145                 rc);
146     break;
147   case GNUNET_SCALARPRODUCT_Status_InvalidResponse:
148     LOG (GNUNET_ERROR_TYPE_ERROR,
149          "Session %s with peer %s failed: invalid response received\n",
150          GNUNET_h2s (&session_key),
151          GNUNET_i2s (&peer_id));
152     break;
153   case GNUNET_SCALARPRODUCT_Status_Failure:
154     LOG (GNUNET_ERROR_TYPE_ERROR,
155          "Session %s with peer %s failed: API failure\n",
156          GNUNET_h2s (&session_key),
157          GNUNET_i2s (&peer_id));
158     break;
159   case GNUNET_SCALARPRODUCT_Status_ServiceDisconnected:
160     LOG (GNUNET_ERROR_TYPE_ERROR,
161          "Session %s with peer %s was disconnected from service.\n",
162          GNUNET_h2s (&session_key),
163          GNUNET_i2s (&peer_id));
164     break;
165   default:
166     LOG (GNUNET_ERROR_TYPE_ERROR,
167          "Session %s with peer %s failed: return code %d\n",
168          GNUNET_h2s (&session_key),
169          GNUNET_i2s (&peer_id),
170          status);
171   }
172   computation = NULL;
173   GNUNET_SCHEDULER_shutdown ();
174 }
175
176
177 /**
178  * Task run during shutdown.
179  *
180  * @param cls unused
181  * @param tc unused
182  */
183 static void
184 shutdown_task (void *cls,
185                const struct GNUNET_SCHEDULER_TaskContext *tc)
186 {
187   if (NULL != computation)
188   {
189     GNUNET_SCALARPRODUCT_cancel (computation);
190     ret = 1; /* aborted */
191   }
192 }
193
194
195 /**
196  * Main function that will be run by the scheduler.
197  *
198  * @param cls closure
199  * @param args remaining command-line arguments
200  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
201  * @param cfg configuration
202  */
203 static void
204 run (void *cls,
205      char *const *args,
206      const char *cfgfile,
207      const struct GNUNET_CONFIGURATION_Handle *cfg)
208 {
209   char *begin = input_elements;
210   char *end;
211   unsigned int i;
212   struct GNUNET_SCALARPRODUCT_Element *elements;
213   uint32_t element_count = 0;
214
215   if (NULL == input_elements)
216   {
217     LOG (GNUNET_ERROR_TYPE_ERROR,
218          _("You must specify at least one message ID to check!\n"));
219     return;
220   }
221   if ( (NULL == input_session_key) ||
222        (0 == strlen (input_session_key)) )
223   {
224     LOG (GNUNET_ERROR_TYPE_ERROR,
225          _("This program needs a session identifier for comparing vectors.\n"));
226     return;
227   }
228   GNUNET_CRYPTO_hash (input_session_key,
229                       strlen (input_session_key),
230                       &session_key);
231   if ( (NULL != input_peer_id) &&
232        (GNUNET_OK !=
233         GNUNET_CRYPTO_eddsa_public_key_from_string (input_peer_id,
234                                                     strlen (input_peer_id),
235                                                     &peer_id.public_key)) )
236   {
237     LOG (GNUNET_ERROR_TYPE_ERROR,
238          _("Tried to set initiator mode, as peer ID was given. "
239            "However, `%s' is not a valid peer identifier.\n"),
240          input_peer_id);
241     return;
242   }
243
244   for (end = begin; 0 != *end; end++)
245     if (*end == ';')
246       element_count++;
247   if (0 == element_count) {
248     LOG (GNUNET_ERROR_TYPE_ERROR,
249          _("Need elements to compute the vectorproduct, got none.\n"));
250     return;
251   }
252
253   elements = GNUNET_malloc (sizeof(struct GNUNET_SCALARPRODUCT_Element) * element_count);
254
255   for (i = 0; i < element_count;i++)
256   {
257     struct GNUNET_SCALARPRODUCT_Element element;
258     char* separator = NULL;
259
260     /* get the length of the current key,value; tupel */
261     for (end = begin; *end != ';'; end++)
262       if (*end == ',')
263         separator = end;
264
265     /* final element */
266     if ( (NULL == separator) ||
267          (begin == separator) ||
268          (separator == end - 1) )
269     {
270       LOG (GNUNET_ERROR_TYPE_ERROR,
271            _("Malformed input, could not parse `%s'\n"),
272            begin);
273       GNUNET_free (elements);
274       return;
275     }
276
277     /* read the element's key */
278     *separator = 0;
279     GNUNET_CRYPTO_hash (begin,
280                         strlen (begin),
281                         &element.key);
282
283     /* read the element's value */
284     if (1 !=
285         sscanf (separator + 1,
286                 "%" SCNd64 ";",
287                 &element.value) )
288     {
289       LOG (GNUNET_ERROR_TYPE_ERROR,
290            _("Could not convert `%s' to int64_t.\n"),
291            begin);
292       GNUNET_free(elements);
293       return;
294     }
295     elements[i] = element;
296     begin = end + 1;
297   }
298
299   if ( ( (NULL != input_peer_id) &&
300          (NULL == (computation
301                    = GNUNET_SCALARPRODUCT_start_computation (cfg,
302                                                              &session_key,
303                                                              &peer_id,
304                                                              elements, element_count,
305                                                              &requester_callback,
306                                                              NULL))) ) ||
307        ( (NULL == input_peer_id) &&
308          (NULL == (computation
309                    = GNUNET_SCALARPRODUCT_accept_computation (cfg,
310                                                               &session_key,
311                                                               elements, element_count,
312                                                               &responder_callback,
313                                                               NULL))) ) )
314   {
315     GNUNET_break (0);
316     GNUNET_free (elements);
317     return;
318   }
319   GNUNET_free (elements);
320   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
321                                 &shutdown_task,
322                                 NULL);
323   ret = 0;
324 }
325
326
327 /**
328  * The main function to the scalarproduct client.
329  *
330  * @param argc number of arguments from the command line
331  * @param argv command line arguments
332  * @return 0 ok, 1 on error
333  */
334 int
335 main (int argc, char *const *argv)
336 {
337   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
338     {'e', "elements", "\"key1,val1;key2,val2;...,keyn,valn;\"",
339       gettext_noop ("A comma separated list of elements to compare as vector with our remote peer."),
340       1, &GNUNET_GETOPT_set_string, &input_elements},
341     {'p', "peer", "PEERID",
342       gettext_noop ("[Optional] peer to calculate our scalarproduct with. If this parameter is not given, the service will wait for a remote peer to compute the request."),
343       1, &GNUNET_GETOPT_set_string, &input_peer_id},
344     {'k', "key", "TRANSACTION_ID",
345       gettext_noop ("Transaction ID shared with peer."),
346       1, &GNUNET_GETOPT_set_string, &input_session_key},
347     GNUNET_GETOPT_OPTION_END
348   };
349
350   return (GNUNET_OK ==
351           GNUNET_PROGRAM_run (argc,
352                               argv,
353                               "gnunet-scalarproduct",
354                               gettext_noop ("Calculate the Vectorproduct with a GNUnet peer."),
355                               options, &run, NULL)) ? ret : 1;
356 }
357
358 /* end of gnunet-scalarproduct.c */