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