SP-service: converted integer types from 16 to 32bit unsigned whereever needed
[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 }
108
109
110 /**
111  * Callback called if we are initiating a new computation session
112  * 
113  * @param cls unused
114  * @param key unused
115  * @param peer unused
116  * @param status if our job was successfully processed 
117  * @param size size of the msg returned
118  * @param msg the response we got.
119  * @param type of the message received 
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 }
153
154 /**
155  * Task run during shutdown.
156  *
157  * @param cls unused
158  * @param tc unused
159  */
160 static void
161 shutdown_task (void *cls,
162                const struct GNUNET_SCHEDULER_TaskContext *tc)
163 {
164   GNUNET_SCALARPRODUCT_disconnect ();
165 }
166
167 /**
168  * Main function that will be run by the scheduler.
169  *
170  * @param cls closure
171  * @param args remaining command-line arguments
172  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
173  * @param cfg configuration
174  */
175 static void
176 run (void *cls,
177      char *const *args,
178      const char *cfgfile,
179      const struct GNUNET_CONFIGURATION_Handle *cfg)
180 {
181   char * begin = input_elements;
182   char * end;
183   int32_t element;
184   int i;
185   int32_t * elements;
186   unsigned char * mask;
187   uint32_t mask_bytes;
188   uint32_t element_count = 0;
189   struct ScalarProductCallbackClosure * closure;
190
191   if (NULL == input_elements)
192   {
193     LOG (GNUNET_ERROR_TYPE_ERROR, _ ("You must specify at least one message ID to check!\n"));
194     return;
195   }
196
197   if (NULL == input_key)
198   {
199     LOG (GNUNET_ERROR_TYPE_ERROR, _ ("This program needs a session identifier for comparing vectors.\n"));
200     return;
201   }
202
203   if (1 > strnlen (input_key, sizeof (struct GNUNET_HashCode)))
204   {
205     LOG (GNUNET_ERROR_TYPE_ERROR, _ ("Please give a session key for --input_key!\n"));
206     return;
207   }
208   closure = GNUNET_new (struct ScalarProductCallbackClosure);
209   GNUNET_CRYPTO_hash (input_key, strlen (input_key), &closure->key);
210
211   if (input_peer_id && GNUNET_OK != GNUNET_CRYPTO_hash_from_string (input_peer_id,
212                                                                     (struct GNUNET_HashCode *) &closure->peer))
213   {
214     LOG (GNUNET_ERROR_TYPE_ERROR, _ ("Tried to set initiator mode, as peer ID was given. "
215                                      "However, `%s' is not a valid peer identifier.\n"),
216          input_peer_id);
217     return;
218   }
219
220   /* Count input_elements_peer1, and put in elements_peer1 array */
221   do
222   {
223     // get the length of the current element and replace , with null
224     for (end = begin; *end && *end != ','; end++);
225
226     if (1 == sscanf (begin, "%" SCNd32",", &element))
227     {
228       //element in the middle
229       element_count++;
230       begin = end + 1;
231     }
232     else if (*begin == 0)
233     {
234       break;
235     }
236     else
237     {
238       LOG (GNUNET_ERROR_TYPE_ERROR, _ ("Could not convert `%s' to int32_t.\n"), begin);
239       return;
240     }
241   }
242   while (1);
243   if (0 == element_count)
244   {
245
246     return;
247   }
248
249   begin = input_elements;
250   elements = GNUNET_malloc (sizeof (int32_t) * element_count);
251   /* Read input_elements_peer1, and put in elements_peer1 array */
252   do
253   {
254     // get the length of the current element and replace , with null
255     for (end = begin; *end && *end != ','; end++);
256
257     if (1 == sscanf (begin, "%" SCNd32",", &element))
258     {
259       //element in the middle
260       element_count++;
261       begin = end + 1;
262     }
263     else if (*begin == 0)
264     {
265       break;
266     }
267   }
268   while (1);
269
270   mask_bytes = element_count / 8 + (element_count % 8 ? 1 : 0);
271   mask = GNUNET_malloc ((element_count / 8) + 2);
272
273   /* Read input_mask_peer1 and read in mask_peer1 array */
274   if ((NULL != input_peer_id) && (NULL != input_mask))
275   {
276     begin = input_mask;
277     unsigned short mask_count = 0;
278
279     do
280     {
281       // get the length of the current element and replace , with null
282       for (end = begin; *end && *end != ','; end++);
283
284       if (1 == sscanf (begin, "%" SCNd32 ",", &element))
285       {
286         //element in the middle
287         begin = end + 1;
288       }
289       else if (*begin == 0)
290       {
291         break;
292       }
293       else
294       {
295         LOG (GNUNET_ERROR_TYPE_ERROR, _ ("Could not convert `%s' to int32_t.\n"), begin);
296         return;
297       }
298
299       if (element)
300         mask[mask_count / 8] = mask[mask_count / 8] | 1 << (mask_count % 8);
301       mask_count++;
302     }
303     while (mask_count < element_count);
304   }
305   else if (NULL != input_peer_id)
306     for (i = 0; i <= mask_bytes; i++)
307       mask[i] = UCHAR_MAX; // all 1's
308
309   if (input_peer_id && (NULL == GNUNET_SCALARPRODUCT_request (cfg,
310                                                               &closure->key,
311                                                               &closure->peer,
312                                                               elements, element_count,
313                                                               mask, mask_bytes,
314                                                               &requester_callback,
315                                                               (void *) &closure)))
316     return;
317
318   if ((NULL == input_peer_id) && (NULL == GNUNET_SCALARPRODUCT_response (cfg,
319                                                                          &closure->key,
320                                                                          elements, element_count,
321                                                                          &responder_callback,
322                                                                          (void *) &closure)))
323     return;
324
325   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
326                                 &shutdown_task,
327                                 NULL);
328   
329   ret = 0;
330 }
331
332
333 /**
334  * The main function to the scalarproduct client.
335  *
336  * @param argc number of arguments from the command line
337  * @param argv command line arguments
338  * @return 0 ok, 1 on error
339  */
340 int
341 main (int argc, char *const *argv)
342 {
343   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
344     {'e', "elements", "\"val1,val2,...,valn\"",
345       gettext_noop ("A comma separated list of elements to compare as vector with our remote peer."),
346       1, &GNUNET_GETOPT_set_string, &input_elements},
347     {'m', "mask", "\"0,1,...,maskn\"",
348       gettext_noop ("A comma separated mask to select which elements should actually be compared."),
349       1, &GNUNET_GETOPT_set_string, &input_mask},
350     {'p', "peer", "PEERID",
351       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."),
352       1, &GNUNET_GETOPT_set_string, &input_peer_id},
353     {'k', "key", "TRANSACTION_ID",
354       gettext_noop ("Transaction ID shared with peer."),
355       1, &GNUNET_GETOPT_set_string, &input_key},
356     GNUNET_GETOPT_OPTION_END
357   };
358
359   return (GNUNET_OK ==
360           GNUNET_PROGRAM_run (argc,
361                               argv,
362                               "gnunet-scalarproduct",
363                               gettext_noop ("Calculate the Vectorproduct with a GNUnet peer."),
364                               options, &run, NULL)) ? ret : 1;
365 }
366