Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / regex / regex_block_lib.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012,2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 /**
19  * @author Bartlomiej Polot
20  * @file regex/regex_block_lib.c
21  * @brief functions for manipulating non-accept blocks stored for
22  *        regex in the DHT
23  */
24 #include "platform.h"
25 #include "regex_block_lib.h"
26 #include "gnunet_constants.h"
27
28 #define LOG(kind,...) GNUNET_log_from (kind,"regex-bck",__VA_ARGS__)
29
30 GNUNET_NETWORK_STRUCT_BEGIN
31
32 /**
33  * Information for each edge.
34  */
35 struct EdgeInfo
36 {
37   /**
38    * Index of the destination of this edge in the
39    * unique destinations array.
40    */
41   uint16_t destination_index GNUNET_PACKED;
42
43   /**
44    * Number of bytes the token for this edge takes in the
45    * token area.
46    */
47   uint16_t token_length GNUNET_PACKED;
48 };
49
50
51 /**
52  * @brief Block to announce a regex state.
53  */
54 struct RegexBlock
55 {
56
57   /**
58    * Length of the proof regex string.
59    */
60   uint16_t proof_len GNUNET_PACKED;
61
62   /**
63    * Is this state an accepting state?
64    */
65   int16_t is_accepting GNUNET_PACKED;
66
67   /**
68    * Number of edges parting from this state.
69    */
70   uint16_t num_edges GNUNET_PACKED;
71
72   /**
73    * Nubmer of unique destinations reachable from this state.
74    */
75   uint16_t num_destinations GNUNET_PACKED;
76
77   /* followed by 'struct GNUNET_HashCode[num_destinations]' */
78
79   /* followed by 'struct EdgeInfo[edge_destination_indices]' */
80
81   /* followed by 'char proof[n_proof]', NOT 0-terminated */
82
83   /* followed by 'char tokens[num_edges][edge_info[k].token_length]';
84      essentially all of the tokens one after the other in the
85      order of the edges; tokens are NOT 0-terminated */
86
87 };
88
89
90 GNUNET_NETWORK_STRUCT_END
91
92
93 /**
94  * Test if this block is marked as being an accept state.
95  *
96  * @param block block to test
97  * @param size number of bytes in block
98  * @return #GNUNET_YES if the block is accepting, #GNUNET_NO if not
99  */
100 int
101 GNUNET_BLOCK_is_accepting (const struct RegexBlock *block,
102                            size_t size)
103 {
104   if (size < sizeof (struct RegexBlock))
105   {
106     GNUNET_break_op (0);
107     return GNUNET_SYSERR;
108   }
109   return ntohs (block->is_accepting);
110 }
111
112
113 /**
114  * Check if the given 'proof' matches the given 'key'.
115  *
116  * @param proof partial regex of a state
117  * @param proof_len number of bytes in 'proof'
118  * @param key hash of a state.
119  * @return #GNUNET_OK if the proof is valid for the given key.
120  */
121 int
122 REGEX_BLOCK_check_proof (const char *proof,
123                          size_t proof_len,
124                          const struct GNUNET_HashCode *key)
125 {
126   struct GNUNET_HashCode key_check;
127
128   if ( (NULL == proof) || (NULL == key))
129   {
130     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n");
131     return GNUNET_NO;
132   }
133   GNUNET_CRYPTO_hash (proof, proof_len, &key_check);
134   return (0 ==
135           GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO;
136 }
137
138
139 /**
140  * Struct to keep track of the xquery while iterating all the edges in a block.
141  */
142 struct CheckEdgeContext
143 {
144   /**
145    * Xquery: string we are looking for.
146    */
147   const char *xquery;
148
149   /**
150    * Has any edge matched the xquery so far? (GNUNET_OK / GNUNET_NO)
151    */
152   int found;
153
154 };
155
156
157 /**
158  * Iterator over all edges in a block, checking for a presence of a given query.
159  *
160  * @param cls Closure, (xquery context).
161  * @param token Token that follows to next state.
162  * @param len Lenght of token.
163  * @param key Hash of next state.
164  *
165  * @return #GNUNET_YES, to keep iterating
166  */
167 static int
168 check_edge (void *cls,
169             const char *token,
170             size_t len,
171             const struct GNUNET_HashCode *key)
172 {
173   struct CheckEdgeContext *ctx = cls;
174
175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
176               "edge %.*s [%u]: %s\n",
177               (int) len,
178               token,
179               (unsigned int) len,
180               GNUNET_h2s (key));
181   if (NULL == ctx->xquery)
182     return GNUNET_YES;
183   if (strlen (ctx->xquery) < len)
184     return GNUNET_YES; /* too long */
185   if (0 == strncmp (ctx->xquery, token, len))
186     ctx->found = GNUNET_OK;
187   return GNUNET_YES; /* keep checking for malformed data! */
188 }
189
190
191 /**
192  * Check if the regex block is well formed, including all edges.
193  *
194  * @param block The start of the block.
195  * @param size The size of the block.
196  * @param query the query for the block
197  * @param xquery String describing the edge we are looking for.
198  *               Can be NULL in case this is a put block.
199  * @return #GNUNET_OK in case it's fine.
200  *         #GNUNET_NO in case the xquery exists and is not found (IRRELEVANT).
201  *         #GNUNET_SYSERR if the block is invalid.
202  */
203 int
204 REGEX_BLOCK_check (const struct RegexBlock *block,
205                    size_t size,
206                    const struct GNUNET_HashCode *query,
207                    const char *xquery)
208 {
209   struct GNUNET_HashCode key;
210   struct CheckEdgeContext ctx;
211   int res;
212
213   LOG (GNUNET_ERROR_TYPE_DEBUG,
214        "Block check\n");
215   if (GNUNET_OK !=
216       REGEX_BLOCK_get_key (block, size,
217                            &key))
218   {
219     GNUNET_break_op (0);
220     return GNUNET_SYSERR;
221   }
222   if (NULL != query &&
223       0 != memcmp (&key,
224                    query,
225                    sizeof (struct GNUNET_HashCode)))
226   {
227     GNUNET_break_op (0);
228     return GNUNET_SYSERR;
229   }
230   if ( (GNUNET_YES == ntohs (block->is_accepting)) &&
231        ( (NULL == xquery) || ('\0' == xquery[0]) ) )
232   {
233     LOG (GNUNET_ERROR_TYPE_DEBUG,
234          "  out! Is accepting: %u, xquery %p\n",
235          ntohs(block->is_accepting),
236          xquery);
237     return GNUNET_OK;
238   }
239   ctx.xquery = xquery;
240   ctx.found = GNUNET_NO;
241   res = REGEX_BLOCK_iterate (block, size, &check_edge, &ctx);
242   if (GNUNET_SYSERR == res)
243     return GNUNET_SYSERR;
244   if (NULL == xquery)
245     return GNUNET_YES;
246   LOG (GNUNET_ERROR_TYPE_DEBUG, "Result %d\n", ctx.found);
247   return ctx.found;
248 }
249
250
251 /**
252  * Obtain the key that a particular block is to be stored under.
253  *
254  * @param block block to get the key from
255  * @param block_len number of bytes in block
256  * @param key where to store the key
257  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block is malformed
258  */
259 int
260 REGEX_BLOCK_get_key (const struct RegexBlock *block,
261                      size_t block_len,
262                      struct GNUNET_HashCode *key)
263 {
264   uint16_t len;
265   const struct GNUNET_HashCode *destinations;
266   const struct EdgeInfo *edges;
267   uint16_t num_destinations;
268   uint16_t num_edges;
269   size_t total;
270
271   if (block_len < sizeof (struct RegexBlock))
272   {
273     GNUNET_break_op (0);
274     return GNUNET_SYSERR;
275   }
276   num_destinations = ntohs (block->num_destinations);
277   num_edges = ntohs (block->num_edges);
278   len = ntohs (block->proof_len);
279   destinations = (const struct GNUNET_HashCode *) &block[1];
280   edges = (const struct EdgeInfo *) &destinations[num_destinations];
281   total = sizeof (struct RegexBlock) + num_destinations * sizeof (struct GNUNET_HashCode) + num_edges * sizeof (struct EdgeInfo) + len;
282   if (block_len < total)
283   {
284     GNUNET_break_op (0);
285     return GNUNET_SYSERR;
286   }
287   GNUNET_CRYPTO_hash (&edges[num_edges], len, key);
288   return GNUNET_OK;
289 }
290
291
292 /**
293  * Iterate over all edges of a block of a regex state.
294  *
295  * @param block Block to iterate over.
296  * @param size Size of @a block.
297  * @param iterator Function to call on each edge in the block.
298  * @param iter_cls Closure for the @a iterator.
299  * @return #GNUNET_SYSERR if an error has been encountered.
300  *         #GNUNET_OK if no error has been encountered.
301  *           Note that if the iterator stops the iteration by returning
302  *         #GNUNET_NO, the block will no longer be checked for further errors.
303  *           The return value will be GNUNET_OK meaning that no errors were
304  *         found until the edge last notified to the iterator, but there might
305  *         be errors in further edges.
306  */
307 int
308 REGEX_BLOCK_iterate (const struct RegexBlock *block,
309                      size_t size,
310                      REGEX_INTERNAL_EgdeIterator iterator,
311                      void *iter_cls)
312 {
313   uint16_t len;
314   const struct GNUNET_HashCode *destinations;
315   const struct EdgeInfo *edges;
316   const char *aux;
317   uint16_t num_destinations;
318   uint16_t num_edges;
319   size_t total;
320   unsigned int n;
321   size_t off;
322
323   LOG (GNUNET_ERROR_TYPE_DEBUG, "Block iterate\n");
324   if (size < sizeof (struct RegexBlock))
325   {
326     GNUNET_break_op (0);
327     return GNUNET_SYSERR;
328   }
329   num_destinations = ntohs (block->num_destinations);
330   num_edges = ntohs (block->num_edges);
331   len = ntohs (block->proof_len);
332   destinations = (const struct GNUNET_HashCode *) &block[1];
333   edges = (const struct EdgeInfo *) &destinations[num_destinations];
334   aux = (const char *) &edges[num_edges];
335   total = sizeof (struct RegexBlock) + num_destinations * sizeof (struct GNUNET_HashCode) + num_edges * sizeof (struct EdgeInfo) + len;
336   if (size < total)
337   {
338     GNUNET_break_op (0);
339     return GNUNET_SYSERR;
340   }
341   for (n=0;n<num_edges;n++)
342     total += ntohs (edges[n].token_length);
343   if (size != total)
344   {
345     fprintf (stderr, "Expected %u, got %u\n",
346              (unsigned int) size,
347              (unsigned int) total);
348     GNUNET_break_op (0);
349     return GNUNET_SYSERR;
350   }
351   off = len;
352   LOG (GNUNET_ERROR_TYPE_DEBUG,
353        "Start iterating block of size %u, proof %u, off %u edges %u\n",
354        size, len, off, n);
355   /* &aux[off] always points to our token */
356   for (n=0;n<num_edges;n++)
357   {
358     LOG (GNUNET_ERROR_TYPE_DEBUG,
359          "Edge %u/%u, off %u tokenlen %u (%.*s)\n",
360          n+1, num_edges, off,
361          ntohs (edges[n].token_length), ntohs (edges[n].token_length),
362          &aux[off]);
363     if (NULL != iterator)
364       if (GNUNET_NO == iterator (iter_cls,
365                                  &aux[off],
366                                  ntohs (edges[n].token_length),
367                                  &destinations[ntohs (edges[n].destination_index)]))
368         return GNUNET_OK;
369     off += ntohs (edges[n].token_length);
370   }
371   return GNUNET_OK;
372 }
373
374
375 /**
376  * Construct a regex block to be stored in the DHT.
377  *
378  * @param proof proof string for the block
379  * @param num_edges number of edges in the block
380  * @param edges the edges of the block
381  * @param accepting is this an accepting state
382  * @param rsize set to the size of the returned block (OUT-only)
383  * @return the regex block, NULL on error
384  */
385 struct RegexBlock *
386 REGEX_BLOCK_create (const char *proof,
387                     unsigned int num_edges,
388                     const struct REGEX_BLOCK_Edge *edges,
389                     int accepting,
390                     size_t *rsize)
391 {
392   struct RegexBlock *block;
393   struct GNUNET_HashCode destinations[1024]; /* 1024 = 64k/64 bytes/key == absolute MAX */
394   uint16_t destination_indices[num_edges];
395   struct GNUNET_HashCode *dests;
396   struct EdgeInfo *edgeinfos;
397   size_t off;
398   size_t len;
399   size_t total;
400   size_t slen;
401   unsigned int unique_destinations;
402   unsigned int j;
403   unsigned int i;
404   char *aux;
405
406   len = strlen (proof);
407   if (len > UINT16_MAX)
408   {
409     GNUNET_break (0);
410     return NULL;
411   }
412   unique_destinations = 0;
413   total = sizeof (struct RegexBlock) + len;
414   for (i=0;i<num_edges;i++)
415   {
416     slen = strlen (edges[i].label);
417     if (slen > UINT16_MAX)
418     {
419       GNUNET_break (0);
420       return NULL;
421     }
422     total += slen;
423     for (j=0;j<unique_destinations;j++)
424       if (0 == memcmp (&destinations[j],
425                        &edges[i].destination,
426                        sizeof (struct GNUNET_HashCode)))
427         break;
428     if (j >= 1024)
429     {
430       GNUNET_break (0);
431       return NULL;
432     }
433     destination_indices[i] = j;
434     if (j == unique_destinations)
435       destinations[unique_destinations++] = edges[i].destination;
436   }
437   total += num_edges * sizeof (struct EdgeInfo) + unique_destinations * sizeof (struct GNUNET_HashCode);
438   if (total >= GNUNET_CONSTANTS_MAX_BLOCK_SIZE)
439   {
440     GNUNET_break (0);
441     return NULL;
442   }
443   block = GNUNET_malloc (total);
444   block->proof_len = htons (len);
445   block->is_accepting = htons (accepting);
446   block->num_edges = htons (num_edges);
447   block->num_destinations = htons (unique_destinations);
448   dests = (struct GNUNET_HashCode *) &block[1];
449   GNUNET_memcpy (dests, destinations, sizeof (struct GNUNET_HashCode) * unique_destinations);
450   edgeinfos = (struct EdgeInfo *) &dests[unique_destinations];
451   aux = (char *) &edgeinfos[num_edges];
452   off = len;
453   GNUNET_memcpy (aux, proof, len);
454   for (i=0;i<num_edges;i++)
455   {
456     slen = strlen (edges[i].label);
457     edgeinfos[i].token_length = htons ((uint16_t) slen);
458     edgeinfos[i].destination_index = htons (destination_indices[i]);
459     GNUNET_memcpy (&aux[off],
460             edges[i].label,
461             slen);
462     off += slen;
463   }
464   *rsize = total;
465   return block;
466 }
467
468
469 /* end of regex_block_lib.c */