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