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