-fix (C) notices
[oweals/gnunet.git] / src / fs / fs_uri.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2003--2014 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file fs/fs_uri.c
23  * @brief Parses and produces uri strings.
24  * @author Igor Wronsky, Christian Grothoff
25  *
26  * GNUnet URIs are of the general form "gnunet://MODULE/IDENTIFIER".
27  * The specific structure of "IDENTIFIER" depends on the module and
28  * maybe differenciated into additional subcategories if applicable.
29  * This module only deals with fs identifiers (MODULE = "fs").
30  * <p>
31  *
32  * This module only parses URIs for the AFS module.  The FS URIs fall
33  * into four categories, "chk", "sks", "ksk" and "loc".  The first three
34  * categories were named in analogy (!) to Freenet, but they do NOT
35  * work in exactly the same way.  They are very similar from the user's
36  * point of view (unique file identifier, subspace, keyword), but the
37  * implementation is rather different in pretty much every detail.
38  * The concrete URI formats are:
39  *
40  * <ul><li>
41  *
42  * First, there are URIs that identify a file.  They have the format
43  * "gnunet://fs/chk/HEX1.HEX2.SIZE".  These URIs can be used to
44  * download the file.  The description, filename, mime-type and other
45  * meta-data is NOT part of the file-URI since a URI uniquely
46  * identifies a resource (and the contents of the file would be the
47  * same even if it had a different description).
48  *
49  * </li><li>
50  *
51  * The second category identifies entries in a namespace.  The format
52  * is "gnunet://fs/sks/NAMESPACE/IDENTIFIER" where the namespace
53  * should be given in HEX.  Applications may allow using a nickname
54  * for the namespace if the nickname is not ambiguous.  The identifier
55  * can be either an ASCII sequence or a HEX-encoding.  If the
56  * identifier is in ASCII but the format is ambiguous and could denote
57  * a HEX-string a "/" is appended to indicate ASCII encoding.
58  *
59  * </li> <li>
60  *
61  * The third category identifies ordinary searches.  The format is
62  * "gnunet://fs/ksk/KEYWORD[+KEYWORD]*".  Using the "+" syntax
63  * it is possible to encode searches with the boolean "AND" operator.
64  * "+" is used since it indicates a commutative 'and' operation and
65  * is unlikely to be used in a keyword by itself.
66  *
67  * </li><li>
68  *
69  * The last category identifies a datum on a specific machine.  The
70  * format is "gnunet://fs/loc/HEX1.HEX2.SIZE.PEER.SIG.EXPTIME".  PEER is
71  * the BinName of the public key of the peer storing the datum.  The
72  * signature (SIG) certifies that this peer has this content.
73  * HEX1, HEX2 and SIZE correspond to a 'chk' URI.
74  *
75  * </li></ul>
76  *
77  * The encoding for hexadecimal values is defined in the hashing.c
78  * module in the gnunetutil library and discussed there.
79  * <p>
80  */
81 #include "platform.h"
82 #include "gnunet_fs_service.h"
83 #include "gnunet_signatures.h"
84 #include "fs_api.h"
85 #include <unitypes.h>
86 #include <unicase.h>
87 #include <uniconv.h>
88 #include <unistr.h>
89 #include <unistdio.h>
90
91
92
93 /**
94  * Get a unique key from a URI.  This is for putting URIs
95  * into HashMaps.  The key may change between FS implementations.
96  *
97  * @param uri uri to convert to a unique key
98  * @param key where to store the unique key
99  */
100 void
101 GNUNET_FS_uri_to_key (const struct GNUNET_FS_Uri *uri,
102                       struct GNUNET_HashCode *key)
103 {
104   switch (uri->type)
105   {
106   case GNUNET_FS_URI_CHK:
107     *key = uri->data.chk.chk.query;
108     return;
109   case GNUNET_FS_URI_SKS:
110     GNUNET_CRYPTO_hash (uri->data.sks.identifier,
111                         strlen (uri->data.sks.identifier), key);
112     break;
113   case GNUNET_FS_URI_KSK:
114     if (uri->data.ksk.keywordCount > 0)
115       GNUNET_CRYPTO_hash (uri->data.ksk.keywords[0],
116                           strlen (uri->data.ksk.keywords[0]), key);
117     break;
118   case GNUNET_FS_URI_LOC:
119     GNUNET_CRYPTO_hash (&uri->data.loc.fi,
120                         sizeof (struct FileIdentifier) +
121                         sizeof (struct GNUNET_PeerIdentity),
122                         key);
123     break;
124   default:
125     memset (key, 0, sizeof (struct GNUNET_HashCode));
126     break;
127   }
128 }
129
130
131 /**
132  * Convert keyword URI to a human readable format
133  * (i.e. the search query that was used in the first place)
134  *
135  * @param uri ksk uri to convert to a string
136  * @return string with the keywords
137  */
138 char *
139 GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri)
140 {
141   size_t n;
142   char *ret;
143   unsigned int i;
144   const char *keyword;
145   char **keywords;
146   unsigned int keywordCount;
147
148   if ((NULL == uri) || (GNUNET_FS_URI_KSK != uri->type))
149   {
150     GNUNET_break (0);
151     return NULL;
152   }
153   keywords = uri->data.ksk.keywords;
154   keywordCount = uri->data.ksk.keywordCount;
155   n = keywordCount + 1;
156   for (i = 0; i < keywordCount; i++)
157   {
158     keyword = keywords[i];
159     n += strlen (keyword) - 1;
160     if (NULL != strstr (&keyword[1], " "))
161       n += 2;
162     if (keyword[0] == '+')
163       n++;
164   }
165   ret = GNUNET_malloc (n);
166   strcpy (ret, "");
167   for (i = 0; i < keywordCount; i++)
168   {
169     keyword = keywords[i];
170     if (NULL != strstr (&keyword[1], " "))
171     {
172       strcat (ret, "\"");
173       if (keyword[0] == '+')
174         strcat (ret, keyword);
175       else
176         strcat (ret, &keyword[1]);
177       strcat (ret, "\"");
178     }
179     else
180     {
181       if (keyword[0] == '+')
182         strcat (ret, keyword);
183       else
184         strcat (ret, &keyword[1]);
185     }
186     strcat (ret, " ");
187   }
188   return ret;
189 }
190
191
192 /**
193  * Given a keyword with %-encoding (and possibly quotes to protect
194  * spaces), return a copy of the keyword without %-encoding and
195  * without double-quotes (%22).  Also, add a space at the beginning
196  * if there is not a '+'.
197  *
198  * @param in string with %-encoding
199  * @param emsg where to store the parser error message (if any)
200  * @return decodded string with leading space (or preserved plus)
201  */
202 static char *
203 percent_decode_keyword (const char *in,
204                         char **emsg)
205 {
206   char *out;
207   char *ret;
208   unsigned int rpos;
209   unsigned int wpos;
210   unsigned int hx;
211
212   out = GNUNET_strdup (in);
213   rpos = 0;
214   wpos = 0;
215   while (out[rpos] != '\0')
216   {
217     if (out[rpos] == '%')
218     {
219       if (1 != SSCANF (&out[rpos + 1], "%2X", &hx))
220       {
221         GNUNET_free (out);
222         *emsg = GNUNET_strdup (_(/* xgettext:no-c-format */
223                                  "Malformed KSK URI (`%' must be followed by HEX number)"));
224         return NULL;
225       }
226       rpos += 3;
227       if (hx == '"')
228         continue;               /* skip double quote */
229       out[wpos++] = (char) hx;
230     }
231     else
232     {
233       out[wpos++] = out[rpos++];
234     }
235   }
236   out[wpos] = '\0';
237   if (out[0] == '+')
238   {
239     ret = GNUNET_strdup (out);
240   }
241   else
242   {
243     /* need to prefix with space */
244     ret = GNUNET_malloc (strlen (out) + 2);
245     strcpy (ret, " ");
246     strcat (ret, out);
247   }
248   GNUNET_free (out);
249   return ret;
250 }
251
252 #define GNUNET_FS_URI_KSK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_KSK_INFIX
253
254 /**
255  * Parse a KSK URI.
256  *
257  * @param s an uri string
258  * @param emsg where to store the parser error message (if any)
259  * @return NULL on error, otherwise the KSK URI
260  */
261 static struct GNUNET_FS_Uri *
262 uri_ksk_parse (const char *s,
263                char **emsg)
264 {
265   struct GNUNET_FS_Uri *ret;
266   char **keywords;
267   unsigned int pos;
268   int max;
269   int iret;
270   int i;
271   size_t slen;
272   char *dup;
273   int saw_quote;
274
275   slen = strlen (s);
276   pos = strlen (GNUNET_FS_URI_KSK_PREFIX);
277   if ((slen <= pos) || (0 != strncmp (s, GNUNET_FS_URI_KSK_PREFIX, pos)))
278     return NULL;                /* not KSK URI */
279   if ((s[slen - 1] == '+') || (s[pos] == '+'))
280   {
281     *emsg =
282         GNUNET_strdup (_("Malformed KSK URI (must not begin or end with `+')"));
283     return NULL;
284   }
285   max = 1;
286   saw_quote = 0;
287   for (i = pos; i < slen; i++)
288   {
289     if ((s[i] == '%') && (&s[i] == strstr (&s[i], "%22")))
290     {
291       saw_quote = (saw_quote + 1) % 2;
292       i += 3;
293       continue;
294     }
295     if ((s[i] == '+') && (saw_quote == 0))
296     {
297       max++;
298       if (s[i - 1] == '+')
299       {
300         *emsg = GNUNET_strdup (_("Malformed KSK URI (`++' not allowed)"));
301         return NULL;
302       }
303     }
304   }
305   if (saw_quote == 1)
306   {
307     *emsg = GNUNET_strdup (_("Malformed KSK URI (quotes not balanced)"));
308     return NULL;
309   }
310   iret = max;
311   dup = GNUNET_strdup (s);
312   keywords = GNUNET_malloc (max * sizeof (char *));
313   for (i = slen - 1; i >= (int) pos; i--)
314   {
315     if ((s[i] == '%') && (&s[i] == strstr (&s[i], "%22")))
316     {
317       saw_quote = (saw_quote + 1) % 2;
318       continue;
319     }
320     if ((dup[i] == '+') && (saw_quote == 0))
321     {
322       keywords[--max] = percent_decode_keyword (&dup[i + 1], emsg);
323       if (NULL == keywords[max])
324         goto CLEANUP;
325       dup[i] = '\0';
326     }
327   }
328   keywords[--max] = percent_decode_keyword (&dup[pos], emsg);
329   if (NULL == keywords[max])
330     goto CLEANUP;
331   GNUNET_assert (0 == max);
332   GNUNET_free (dup);
333   ret = GNUNET_new (struct GNUNET_FS_Uri);
334   ret->type = GNUNET_FS_URI_KSK;
335   ret->data.ksk.keywordCount = iret;
336   ret->data.ksk.keywords = keywords;
337   return ret;
338 CLEANUP:
339   for (i = 0; i < max; i++)
340     GNUNET_free_non_null (keywords[i]);
341   GNUNET_free (keywords);
342   GNUNET_free (dup);
343   return NULL;
344 }
345
346
347 #define GNUNET_FS_URI_SKS_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_SKS_INFIX
348
349 /**
350  * Parse an SKS URI.
351  *
352  * @param s an uri string
353  * @param emsg where to store the parser error message (if any)
354  * @return NULL on error, SKS URI otherwise
355  */
356 static struct GNUNET_FS_Uri *
357 uri_sks_parse (const char *s,
358                char **emsg)
359 {
360   struct GNUNET_FS_Uri *ret;
361   struct GNUNET_CRYPTO_EcdsaPublicKey ns;
362   size_t pos;
363   char *end;
364
365   pos = strlen (GNUNET_FS_URI_SKS_PREFIX);
366   if ((strlen (s) <= pos) || (0 != strncmp (s, GNUNET_FS_URI_SKS_PREFIX, pos)))
367     return NULL;                /* not an SKS URI */
368   end = strchr (&s[pos], '/');
369   if ( (NULL == end) ||
370        (GNUNET_OK !=
371         GNUNET_STRINGS_string_to_data (&s[pos],
372                                        end - &s[pos],
373                                        &ns,
374                                        sizeof (ns))) )
375   {
376     *emsg = GNUNET_strdup (_("Malformed SKS URI (wrong syntax)"));
377     return NULL; /* malformed */
378   }
379   end++; /* skip over '/' */
380   ret = GNUNET_new (struct GNUNET_FS_Uri);
381   ret->type = GNUNET_FS_URI_SKS;
382   ret->data.sks.ns = ns;
383   ret->data.sks.identifier = GNUNET_strdup (end);
384   return ret;
385 }
386
387 #define GNUNET_FS_URI_CHK_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_CHK_INFIX
388
389
390 /**
391  * Parse a CHK URI.
392  *
393  * @param s an uri string
394  * @param emsg where to store the parser error message (if any)
395  * @return NULL on error, CHK URI otherwise
396  */
397 static struct GNUNET_FS_Uri *
398 uri_chk_parse (const char *s,
399                char **emsg)
400 {
401   struct GNUNET_FS_Uri *ret;
402   struct FileIdentifier fi;
403   unsigned int pos;
404   unsigned long long flen;
405   size_t slen;
406   char h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
407   char h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
408
409   slen = strlen (s);
410   pos = strlen (GNUNET_FS_URI_CHK_PREFIX);
411   if ((slen < pos + 2 * sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) ||
412       (0 != strncmp (s, GNUNET_FS_URI_CHK_PREFIX, pos)))
413     return NULL;                /* not a CHK URI */
414   if ((s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') ||
415       (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.'))
416   {
417     *emsg = GNUNET_strdup (_("Malformed CHK URI (wrong syntax)"));
418     return NULL;
419   }
420   memcpy (h1, &s[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
421   h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
422   memcpy (h2, &s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)],
423           sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
424   h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
425
426   if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h1, &fi.chk.key)) ||
427       (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h2, &fi.chk.query)) ||
428       (1 !=
429        SSCANF (&s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2],
430                "%llu", &flen)))
431   {
432     *emsg = GNUNET_strdup (_("Malformed CHK URI (failed to decode CHK)"));
433     return NULL;
434   }
435   fi.file_length = GNUNET_htonll (flen);
436   ret = GNUNET_new (struct GNUNET_FS_Uri);
437   ret->type = GNUNET_FS_URI_CHK;
438   ret->data.chk = fi;
439   return ret;
440 }
441
442
443 GNUNET_NETWORK_STRUCT_BEGIN
444 /**
445  * Structure that defines how the contents of a location URI must be
446  * assembled in memory to create or verify the signature of a location
447  * URI.
448  */
449 struct LocUriAssembly
450 {
451   /**
452    * What is being signed (rest of this struct).
453    */
454   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
455
456   /**
457    * Expiration time of the offer.
458    */
459   struct GNUNET_TIME_AbsoluteNBO exptime;
460
461   /**
462    * File being offered.
463    */
464   struct FileIdentifier fi;
465
466   /**
467    * Peer offering the file.
468    */
469   struct GNUNET_PeerIdentity peer;
470
471 };
472 GNUNET_NETWORK_STRUCT_END
473
474
475 #define GNUNET_FS_URI_LOC_PREFIX GNUNET_FS_URI_PREFIX GNUNET_FS_URI_LOC_INFIX
476
477 #define SIGNATURE_ASCII_LENGTH 103
478
479 /**
480  * Parse a LOC URI.
481  * Also verifies validity of the location URI.
482  *
483  * @param s an uri string
484  * @param emsg where to store the parser error message (if any)
485  * @return NULL on error, valid LOC URI otherwise
486  */
487 static struct GNUNET_FS_Uri *
488 uri_loc_parse (const char *s,
489                char **emsg)
490 {
491   struct GNUNET_FS_Uri *uri;
492   char h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
493   char h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
494   unsigned int pos;
495   unsigned int npos;
496   unsigned long long exptime;
497   unsigned long long flen;
498   struct GNUNET_TIME_Absolute et;
499   struct GNUNET_CRYPTO_EddsaSignature sig;
500   struct LocUriAssembly ass;
501   size_t slen;
502
503   slen = strlen (s);
504   pos = strlen (GNUNET_FS_URI_LOC_PREFIX);
505   if ((slen < pos + 2 * sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) ||
506       (0 != strncmp (s, GNUNET_FS_URI_LOC_PREFIX, pos)))
507     return NULL;                /* not a LOC URI */
508   if ((s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') ||
509       (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.'))
510   {
511     *emsg = GNUNET_strdup (_("LOC URI malformed (wrong syntax)"));
512     return NULL;
513   }
514   memcpy (h1, &s[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
515   h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
516   memcpy (h2, &s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)],
517           sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded));
518   h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0';
519
520   if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h1, &ass.fi.chk.key)) ||
521       (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h2, &ass.fi.chk.query)) ||
522       (1 !=
523        SSCANF (&s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2],
524                "%llu", &flen)))
525   {
526     *emsg = GNUNET_strdup (_("LOC URI malformed (no CHK)"));
527     return NULL;
528   }
529   ass.fi.file_length = GNUNET_htonll (flen);
530
531   npos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2;
532   while ((s[npos] != '\0') && (s[npos] != '.'))
533     npos++;
534   if (s[npos] == '\0')
535   {
536     *emsg = GNUNET_strdup (_("LOC URI malformed (missing LOC)"));
537     goto ERR;
538   }
539   npos++;
540   if ( (strlen (&s[npos]) <= GNUNET_CRYPTO_PKEY_ASCII_LENGTH + 1) ||
541        ('.' != s[npos+GNUNET_CRYPTO_PKEY_ASCII_LENGTH]) )
542   {
543     *emsg =
544       GNUNET_strdup (_("LOC URI malformed (wrong syntax for public key)"));
545   }
546   if (GNUNET_OK !=
547       GNUNET_CRYPTO_eddsa_public_key_from_string (&s[npos],
548                                                   GNUNET_CRYPTO_PKEY_ASCII_LENGTH,
549                                                   &ass.peer.public_key))
550   {
551     *emsg =
552         GNUNET_strdup (_("LOC URI malformed (could not decode public key)"));
553     goto ERR;
554   }
555   npos += GNUNET_CRYPTO_PKEY_ASCII_LENGTH;
556   if (s[npos++] != '.')
557   {
558     *emsg = GNUNET_strdup (_("LOC URI malformed (could not find signature)"));
559     goto ERR;
560   }
561   if ( (strlen (&s[npos]) <= SIGNATURE_ASCII_LENGTH + 1) ||
562        ('.' != s[npos + SIGNATURE_ASCII_LENGTH]) )
563   {
564     *emsg = GNUNET_strdup (_("LOC URI malformed (wrong syntax for signature)"));
565     goto ERR;
566   }
567   if (GNUNET_OK !=
568       GNUNET_STRINGS_string_to_data (&s[npos],
569                                      SIGNATURE_ASCII_LENGTH,
570                                      &sig,
571                                      sizeof (struct GNUNET_CRYPTO_EddsaSignature)))
572   {
573     *emsg = GNUNET_strdup (_("LOC URI malformed (could not decode signature)"));
574     goto ERR;
575   }
576   npos += SIGNATURE_ASCII_LENGTH;
577   if (s[npos++] != '.')
578   {
579     *emsg = GNUNET_strdup (_("LOC URI malformed (wrong syntax for expiration time)"));
580     goto ERR;
581   }
582   if (1 != SSCANF (&s[npos], "%llu", &exptime))
583   {
584     *emsg =
585         GNUNET_strdup (_("LOC URI malformed (could not parse expiration time)"));
586     goto ERR;
587   }
588   ass.purpose.size = htonl (sizeof (struct LocUriAssembly));
589   ass.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT);
590   et.abs_value_us = exptime * 1000LL * 1000LL;
591   ass.exptime = GNUNET_TIME_absolute_hton (et);
592   if (GNUNET_OK !=
593       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT,
594                                   &ass.purpose, &sig, &ass.peer.public_key))
595   {
596     *emsg =
597         GNUNET_strdup (_("LOC URI malformed (signature failed validation)"));
598     goto ERR;
599   }
600   uri = GNUNET_new (struct GNUNET_FS_Uri);
601   uri->type = GNUNET_FS_URI_LOC;
602   uri->data.loc.fi = ass.fi;
603   uri->data.loc.peer = ass.peer;
604   uri->data.loc.expirationTime = et;
605   uri->data.loc.contentSignature = sig;
606
607   return uri;
608 ERR:
609   return NULL;
610 }
611
612
613 /**
614  * Convert a UTF-8 String to a URI.
615  *
616  * @param uri string to parse
617  * @param emsg where to store the parser error message (if any)
618  * @return NULL on error
619  */
620 struct GNUNET_FS_Uri *
621 GNUNET_FS_uri_parse (const char *uri,
622                      char **emsg)
623 {
624   struct GNUNET_FS_Uri *ret;
625   char *msg;
626
627   if (NULL == uri)
628   {
629     GNUNET_break (0);
630     if (NULL != emsg)
631       *emsg = GNUNET_strdup (_("invalid argument"));
632     return NULL;
633   }
634   if (NULL == emsg)
635     emsg = &msg;
636   *emsg = NULL;
637   if ((NULL != (ret = uri_chk_parse (uri, emsg))) ||
638       (NULL != (ret = uri_ksk_parse (uri, emsg))) ||
639       (NULL != (ret = uri_sks_parse (uri, emsg))) ||
640       (NULL != (ret = uri_loc_parse (uri, emsg))))
641     return ret;
642   if (NULL == *emsg)
643     *emsg = GNUNET_strdup (_("Unrecognized URI type"));
644   if (emsg == &msg)
645     GNUNET_free (msg);
646   return NULL;
647 }
648
649
650 /**
651  * Free URI.
652  *
653  * @param uri uri to free
654  */
655 void
656 GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri)
657 {
658   unsigned int i;
659
660   switch (uri->type)
661   {
662   case GNUNET_FS_URI_KSK:
663     for (i = 0; i < uri->data.ksk.keywordCount; i++)
664       GNUNET_free (uri->data.ksk.keywords[i]);
665     GNUNET_array_grow (uri->data.ksk.keywords, uri->data.ksk.keywordCount, 0);
666     break;
667   case GNUNET_FS_URI_SKS:
668     GNUNET_free (uri->data.sks.identifier);
669     break;
670   case GNUNET_FS_URI_LOC:
671     break;
672   default:
673     /* do nothing */
674     break;
675   }
676   GNUNET_free (uri);
677 }
678
679
680 /**
681  * How many keywords are ANDed in this keyword URI?
682  *
683  * @param uri ksk uri to get the number of keywords from
684  * @return 0 if this is not a keyword URI
685  */
686 unsigned int
687 GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri)
688 {
689   if (uri->type != GNUNET_FS_URI_KSK)
690     return 0;
691   return uri->data.ksk.keywordCount;
692 }
693
694
695 /**
696  * Iterate over all keywords in this keyword URI.
697  *
698  * @param uri ksk uri to get the keywords from
699  * @param iterator function to call on each keyword
700  * @param iterator_cls closure for iterator
701  * @return -1 if this is not a keyword URI, otherwise number of
702  *   keywords iterated over until iterator aborted
703  */
704 int
705 GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri,
706                                 GNUNET_FS_KeywordIterator iterator,
707                                 void *iterator_cls)
708 {
709   unsigned int i;
710   char *keyword;
711
712   if (uri->type != GNUNET_FS_URI_KSK)
713     return -1;
714   if (NULL == iterator)
715     return uri->data.ksk.keywordCount;
716   for (i = 0; i < uri->data.ksk.keywordCount; i++)
717   {
718     keyword = uri->data.ksk.keywords[i];
719     /* first character of keyword indicates
720      * if it is mandatory or not */
721     if (GNUNET_OK != iterator (iterator_cls, &keyword[1], keyword[0] == '+'))
722       return i;
723   }
724   return i;
725 }
726
727
728 /**
729  * Add the given keyword to the set of keywords represented by the URI.
730  * Does nothing if the keyword is already present.
731  *
732  * @param uri ksk uri to modify
733  * @param keyword keyword to add
734  * @param is_mandatory is this keyword mandatory?
735  */
736 void
737 GNUNET_FS_uri_ksk_add_keyword (struct GNUNET_FS_Uri *uri,
738                                const char *keyword,
739                                int is_mandatory)
740 {
741   unsigned int i;
742   const char *old;
743   char *n;
744
745   GNUNET_assert (uri->type == GNUNET_FS_URI_KSK);
746   for (i = 0; i < uri->data.ksk.keywordCount; i++)
747   {
748     old = uri->data.ksk.keywords[i];
749     if (0 == strcmp (&old[1], keyword))
750       return;
751   }
752   GNUNET_asprintf (&n, is_mandatory ? "+%s" : " %s", keyword);
753   GNUNET_array_append (uri->data.ksk.keywords, uri->data.ksk.keywordCount, n);
754 }
755
756
757 /**
758  * Remove the given keyword from the set of keywords represented by the URI.
759  * Does nothing if the keyword is not present.
760  *
761  * @param uri ksk uri to modify
762  * @param keyword keyword to add
763  */
764 void
765 GNUNET_FS_uri_ksk_remove_keyword (struct GNUNET_FS_Uri *uri,
766                                   const char *keyword)
767 {
768   unsigned int i;
769   char *old;
770
771   GNUNET_assert (uri->type == GNUNET_FS_URI_KSK);
772   for (i = 0; i < uri->data.ksk.keywordCount; i++)
773   {
774     old = uri->data.ksk.keywords[i];
775     if (0 == strcmp (&old[1], keyword))
776     {
777       uri->data.ksk.keywords[i] =
778           uri->data.ksk.keywords[uri->data.ksk.keywordCount - 1];
779       GNUNET_array_grow (uri->data.ksk.keywords, uri->data.ksk.keywordCount,
780                          uri->data.ksk.keywordCount - 1);
781       GNUNET_free (old);
782       return;
783     }
784   }
785 }
786
787
788 /**
789  * Obtain the identity of the peer offering the data
790  *
791  * @param uri the location URI to inspect
792  * @param peer where to store the identify of the peer (presumably) offering the content
793  * @return #GNUNET_SYSERR if this is not a location URI, otherwise #GNUNET_OK
794  */
795 int
796 GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri,
797                                      struct GNUNET_PeerIdentity *peer)
798 {
799   if (uri->type != GNUNET_FS_URI_LOC)
800     return GNUNET_SYSERR;
801   *peer = uri->data.loc.peer;
802   return GNUNET_OK;
803 }
804
805
806 /**
807  * Obtain the expiration of the LOC URI.
808  *
809  * @param uri location URI to get the expiration from
810  * @return expiration time of the URI
811  */
812 struct GNUNET_TIME_Absolute
813 GNUNET_FS_uri_loc_get_expiration (const struct GNUNET_FS_Uri *uri)
814 {
815   GNUNET_assert (uri->type == GNUNET_FS_URI_LOC);
816   return uri->data.loc.expirationTime;
817 }
818
819
820 /**
821  * Obtain the URI of the content itself.
822  *
823  * @param uri location URI to get the content URI from
824  * @return NULL if argument is not a location URI
825  */
826 struct GNUNET_FS_Uri *
827 GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri)
828 {
829   struct GNUNET_FS_Uri *ret;
830
831   if (uri->type != GNUNET_FS_URI_LOC)
832     return NULL;
833   ret = GNUNET_new (struct GNUNET_FS_Uri);
834   ret->type = GNUNET_FS_URI_CHK;
835   ret->data.chk = uri->data.loc.fi;
836   return ret;
837 }
838
839
840 /**
841  * Construct a location URI (this peer will be used for the location).
842  * This function should only be called from within gnunet-service-fs,
843  * as it requires the peer's private key which is generally unavailable
844  * to processes directly under the user's control.  However, for
845  * testing and as it logically fits under URIs, it is in this API.
846  *
847  * @param base_uri content offered by the sender
848  * @param sign_key private key of the peer
849  * @param expiration_time how long will the content be offered?
850  * @return the location URI, NULL on error
851  */
852 struct GNUNET_FS_Uri *
853 GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri,
854                           const struct GNUNET_CRYPTO_EddsaPrivateKey *sign_key,
855                           struct GNUNET_TIME_Absolute expiration_time)
856 {
857   struct GNUNET_FS_Uri *uri;
858   struct GNUNET_CRYPTO_EddsaPublicKey my_public_key;
859   struct LocUriAssembly ass;
860   struct GNUNET_TIME_Absolute et;
861
862   if (GNUNET_FS_URI_CHK != base_uri->type)
863     return NULL;
864   /* we round expiration time to full seconds for SKS URIs */
865   et.abs_value_us = (expiration_time.abs_value_us / 1000000LL) * 1000000LL;
866   GNUNET_CRYPTO_eddsa_key_get_public (sign_key,
867                                       &my_public_key);
868   ass.purpose.size = htonl (sizeof (struct LocUriAssembly));
869   ass.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT);
870   ass.exptime = GNUNET_TIME_absolute_hton (et);
871   ass.fi = base_uri->data.chk;
872   ass.peer.public_key = my_public_key;
873   uri = GNUNET_new (struct GNUNET_FS_Uri);
874   uri->type = GNUNET_FS_URI_LOC;
875   uri->data.loc.fi = base_uri->data.chk;
876   uri->data.loc.expirationTime = et;
877   uri->data.loc.peer.public_key = my_public_key;
878   GNUNET_assert (GNUNET_OK ==
879                  GNUNET_CRYPTO_eddsa_sign (sign_key,
880                                            &ass.purpose,
881                                            &uri->data.loc.contentSignature));
882   return uri;
883 }
884
885
886 /**
887  * Create an SKS URI from a namespace ID and an identifier.
888  *
889  * @param ns namespace ID
890  * @param id identifier
891  * @return an FS URI for the given namespace and identifier
892  */
893 struct GNUNET_FS_Uri *
894 GNUNET_FS_uri_sks_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *ns,
895                           const char *id)
896 {
897   struct GNUNET_FS_Uri *ns_uri;
898
899   ns_uri = GNUNET_new (struct GNUNET_FS_Uri);
900   ns_uri->type = GNUNET_FS_URI_SKS;
901   ns_uri->data.sks.ns = *ns;
902   ns_uri->data.sks.identifier = GNUNET_strdup (id);
903   return ns_uri;
904 }
905
906
907 /**
908  * Merge the sets of keywords from two KSK URIs.
909  * (useful for merging the canonicalized keywords with
910  * the original keywords for sharing).
911  *
912  * @param u1 first uri
913  * @param u2 second uri
914  * @return merged URI, NULL on error
915  */
916 struct GNUNET_FS_Uri *
917 GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1,
918                          const struct GNUNET_FS_Uri *u2)
919 {
920   struct GNUNET_FS_Uri *ret;
921   unsigned int kc;
922   unsigned int i;
923   unsigned int j;
924   int found;
925   const char *kp;
926   char **kl;
927
928   if ((u1 == NULL) && (u2 == NULL))
929     return NULL;
930   if (u1 == NULL)
931     return GNUNET_FS_uri_dup (u2);
932   if (u2 == NULL)
933     return GNUNET_FS_uri_dup (u1);
934   if ((u1->type != GNUNET_FS_URI_KSK) || (u2->type != GNUNET_FS_URI_KSK))
935   {
936     GNUNET_break (0);
937     return NULL;
938   }
939   kc = u1->data.ksk.keywordCount;
940   kl = GNUNET_malloc ((kc + u2->data.ksk.keywordCount) * sizeof (char *));
941   for (i = 0; i < u1->data.ksk.keywordCount; i++)
942     kl[i] = GNUNET_strdup (u1->data.ksk.keywords[i]);
943   for (i = 0; i < u2->data.ksk.keywordCount; i++)
944   {
945     kp = u2->data.ksk.keywords[i];
946     found = 0;
947     for (j = 0; j < u1->data.ksk.keywordCount; j++)
948       if (0 == strcmp (kp + 1, kl[j] + 1))
949       {
950         found = 1;
951         if (kp[0] == '+')
952           kl[j][0] = '+';
953         break;
954       }
955     if (0 == found)
956       kl[kc++] = GNUNET_strdup (kp);
957   }
958   ret = GNUNET_new (struct GNUNET_FS_Uri);
959   ret->type = GNUNET_FS_URI_KSK;
960   ret->data.ksk.keywordCount = kc;
961   ret->data.ksk.keywords = kl;
962   return ret;
963 }
964
965
966 /**
967  * Duplicate URI.
968  *
969  * @param uri the URI to duplicate
970  * @return copy of the URI
971  */
972 struct GNUNET_FS_Uri *
973 GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri)
974 {
975   struct GNUNET_FS_Uri *ret;
976   unsigned int i;
977
978   if (uri == NULL)
979     return NULL;
980   ret = GNUNET_new (struct GNUNET_FS_Uri);
981   memcpy (ret, uri, sizeof (struct GNUNET_FS_Uri));
982   switch (ret->type)
983   {
984   case GNUNET_FS_URI_KSK:
985     if (ret->data.ksk.keywordCount >=
986         GNUNET_MAX_MALLOC_CHECKED / sizeof (char *))
987     {
988       GNUNET_break (0);
989       GNUNET_free (ret);
990       return NULL;
991     }
992     if (ret->data.ksk.keywordCount > 0)
993     {
994       ret->data.ksk.keywords =
995           GNUNET_malloc (ret->data.ksk.keywordCount * sizeof (char *));
996       for (i = 0; i < ret->data.ksk.keywordCount; i++)
997         ret->data.ksk.keywords[i] = GNUNET_strdup (uri->data.ksk.keywords[i]);
998     }
999     else
1000       ret->data.ksk.keywords = NULL;    /* just to be sure */
1001     break;
1002   case GNUNET_FS_URI_SKS:
1003     ret->data.sks.identifier = GNUNET_strdup (uri->data.sks.identifier);
1004     break;
1005   case GNUNET_FS_URI_LOC:
1006     break;
1007   default:
1008     break;
1009   }
1010   return ret;
1011 }
1012
1013
1014 /**
1015  * Create an FS URI from a single user-supplied string of keywords.
1016  * The string is broken up at spaces into individual keywords.
1017  * Keywords that start with "+" are mandatory.  Double-quotes can
1018  * be used to prevent breaking up strings at spaces (and also
1019  * to specify non-mandatory keywords starting with "+").
1020  *
1021  * Keywords must contain a balanced number of double quotes and
1022  * double quotes can not be used in the actual keywords (for
1023  * example, the string '""foo bar""' will be turned into two
1024  * "OR"ed keywords 'foo' and 'bar', not into '"foo bar"'.
1025  *
1026  * @param keywords the keyword string
1027  * @param emsg where to store an error message
1028  * @return an FS URI for the given keywords, NULL
1029  *  if keywords is not legal (i.e. empty).
1030  */
1031 struct GNUNET_FS_Uri *
1032 GNUNET_FS_uri_ksk_create (const char *keywords,
1033                           char **emsg)
1034 {
1035   char **keywordarr;
1036   unsigned int num_Words;
1037   int inWord;
1038   char *pos;
1039   struct GNUNET_FS_Uri *uri;
1040   char *searchString;
1041   int saw_quote;
1042
1043   if (keywords == NULL)
1044   {
1045     *emsg = GNUNET_strdup (_("No keywords specified!\n"));
1046     GNUNET_break (0);
1047     return NULL;
1048   }
1049   searchString = GNUNET_strdup (keywords);
1050   num_Words = 0;
1051   inWord = 0;
1052   saw_quote = 0;
1053   pos = searchString;
1054   while ('\0' != *pos)
1055   {
1056     if ((saw_quote == 0) && (isspace ((unsigned char) *pos)))
1057     {
1058       inWord = 0;
1059     }
1060     else if (0 == inWord)
1061     {
1062       inWord = 1;
1063       ++num_Words;
1064     }
1065     if ('"' == *pos)
1066       saw_quote = (saw_quote + 1) % 2;
1067     pos++;
1068   }
1069   if (num_Words == 0)
1070   {
1071     GNUNET_free (searchString);
1072     *emsg = GNUNET_strdup (_("No keywords specified!\n"));
1073     return NULL;
1074   }
1075   if (saw_quote != 0)
1076   {
1077     GNUNET_free (searchString);
1078     *emsg = GNUNET_strdup (_("Number of double-quotes not balanced!\n"));
1079     return NULL;
1080   }
1081   keywordarr = GNUNET_malloc (num_Words * sizeof (char *));
1082   num_Words = 0;
1083   inWord = 0;
1084   pos = searchString;
1085   while ('\0' != *pos)
1086   {
1087     if ((saw_quote == 0) && (isspace ((unsigned char) *pos)))
1088     {
1089       inWord = 0;
1090       *pos = '\0';
1091     }
1092     else if (0 == inWord)
1093     {
1094       keywordarr[num_Words] = pos;
1095       inWord = 1;
1096       ++num_Words;
1097     }
1098     if ('"' == *pos)
1099       saw_quote = (saw_quote + 1) % 2;
1100     pos++;
1101   }
1102   uri =
1103       GNUNET_FS_uri_ksk_create_from_args (num_Words,
1104                                           (const char **) keywordarr);
1105   GNUNET_free (keywordarr);
1106   GNUNET_free (searchString);
1107   return uri;
1108 }
1109
1110
1111 /**
1112  * Create an FS URI from a user-supplied command line of keywords.
1113  * Arguments should start with "+" to indicate mandatory
1114  * keywords.
1115  *
1116  * @param argc number of keywords
1117  * @param argv keywords (double quotes are not required for
1118  *             keywords containing spaces; however, double
1119  *             quotes are required for keywords starting with
1120  *             "+"); there is no mechanism for having double
1121  *             quotes in the actual keywords (if the user
1122  *             did specifically specify double quotes, the
1123  *             caller should convert each double quote
1124  *             into two single quotes).
1125  * @return an FS URI for the given keywords, NULL
1126  *  if keywords is not legal (i.e. empty).
1127  */
1128 struct GNUNET_FS_Uri *
1129 GNUNET_FS_uri_ksk_create_from_args (unsigned int argc,
1130                                     const char **argv)
1131 {
1132   unsigned int i;
1133   struct GNUNET_FS_Uri *uri;
1134   const char *keyword;
1135   char *val;
1136   const char *r;
1137   char *w;
1138   char *emsg;
1139
1140   if (argc == 0)
1141     return NULL;
1142   /* allow URI to be given as one and only keyword and
1143    * handle accordingly */
1144   emsg = NULL;
1145   if ((argc == 1) && (strlen (argv[0]) > strlen (GNUNET_FS_URI_PREFIX)) &&
1146       (0 ==
1147        strncmp (argv[0], GNUNET_FS_URI_PREFIX, strlen (GNUNET_FS_URI_PREFIX)))
1148       && (NULL != (uri = GNUNET_FS_uri_parse (argv[0], &emsg))))
1149     return uri;
1150   GNUNET_free_non_null (emsg);
1151   uri = GNUNET_new (struct GNUNET_FS_Uri);
1152   uri->type = GNUNET_FS_URI_KSK;
1153   uri->data.ksk.keywordCount = argc;
1154   uri->data.ksk.keywords = GNUNET_malloc (argc * sizeof (char *));
1155   for (i = 0; i < argc; i++)
1156   {
1157     keyword = argv[i];
1158     if (keyword[0] == '+')
1159       val = GNUNET_strdup (keyword);
1160     else
1161       GNUNET_asprintf (&val, " %s", keyword);
1162     r = val;
1163     w = val;
1164     while ('\0' != *r)
1165     {
1166       if ('"' == *r)
1167         r++;
1168       else
1169         *(w++) = *(r++);
1170     }
1171     *w = '\0';
1172     uri->data.ksk.keywords[i] = val;
1173   }
1174   return uri;
1175 }
1176
1177
1178 /**
1179  * Test if two URIs are equal.
1180  *
1181  * @param u1 one of the URIs
1182  * @param u2 the other URI
1183  * @return #GNUNET_YES if the URIs are equal
1184  */
1185 int
1186 GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1,
1187                           const struct GNUNET_FS_Uri *u2)
1188 {
1189   int ret;
1190   unsigned int i;
1191   unsigned int j;
1192
1193   GNUNET_assert (u1 != NULL);
1194   GNUNET_assert (u2 != NULL);
1195   if (u1->type != u2->type)
1196     return GNUNET_NO;
1197   switch (u1->type)
1198   {
1199   case GNUNET_FS_URI_CHK:
1200     if (0 ==
1201         memcmp (&u1->data.chk, &u2->data.chk, sizeof (struct FileIdentifier)))
1202       return GNUNET_YES;
1203     return GNUNET_NO;
1204   case GNUNET_FS_URI_SKS:
1205     if ((0 ==
1206          memcmp (&u1->data.sks.ns, &u2->data.sks.ns,
1207                  sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) &&
1208         (0 == strcmp (u1->data.sks.identifier, u2->data.sks.identifier)))
1209
1210       return GNUNET_YES;
1211     return GNUNET_NO;
1212   case GNUNET_FS_URI_KSK:
1213     if (u1->data.ksk.keywordCount != u2->data.ksk.keywordCount)
1214       return GNUNET_NO;
1215     for (i = 0; i < u1->data.ksk.keywordCount; i++)
1216     {
1217       ret = GNUNET_NO;
1218       for (j = 0; j < u2->data.ksk.keywordCount; j++)
1219       {
1220         if (0 == strcmp (u1->data.ksk.keywords[i], u2->data.ksk.keywords[j]))
1221         {
1222           ret = GNUNET_YES;
1223           break;
1224         }
1225       }
1226       if (ret == GNUNET_NO)
1227         return GNUNET_NO;
1228     }
1229     return GNUNET_YES;
1230   case GNUNET_FS_URI_LOC:
1231     if (memcmp
1232         (&u1->data.loc, &u2->data.loc,
1233          sizeof (struct FileIdentifier) +
1234          sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
1235          sizeof (struct GNUNET_TIME_Absolute) + sizeof (unsigned short) +
1236          sizeof (unsigned short)) != 0)
1237       return GNUNET_NO;
1238     return GNUNET_YES;
1239   default:
1240     return GNUNET_NO;
1241   }
1242 }
1243
1244
1245 /**
1246  * Is this a namespace URI?
1247  *
1248  * @param uri the uri to check
1249  * @return #GNUNET_YES if this is an SKS uri
1250  */
1251 int
1252 GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri)
1253 {
1254   return uri->type == GNUNET_FS_URI_SKS;
1255 }
1256
1257
1258 /**
1259  * Get the ID of a namespace from the given
1260  * namespace URI.
1261  *
1262  * @param uri the uri to get the namespace ID from
1263  * @param pseudonym where to store the ID of the namespace
1264  * @return #GNUNET_OK on success
1265  */
1266 int
1267 GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri,
1268                                  struct GNUNET_CRYPTO_EcdsaPublicKey *pseudonym)
1269 {
1270   if (!GNUNET_FS_uri_test_sks (uri))
1271   {
1272     GNUNET_break (0);
1273     return GNUNET_SYSERR;
1274   }
1275   *pseudonym = uri->data.sks.ns;
1276   return GNUNET_OK;
1277 }
1278
1279
1280 /**
1281  * Get the content identifier of an SKS URI.
1282  *
1283  * @param uri the sks uri
1284  * @return NULL on error (not a valid SKS URI)
1285  */
1286 char *
1287 GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri)
1288 {
1289   if (!GNUNET_FS_uri_test_sks (uri))
1290   {
1291     GNUNET_break (0);
1292     return NULL;
1293   }
1294   return GNUNET_strdup (uri->data.sks.identifier);
1295 }
1296
1297
1298 /**
1299  * Is this a keyword URI?
1300  *
1301  * @param uri the uri
1302  * @return #GNUNET_YES if this is a KSK uri
1303  */
1304 int
1305 GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri)
1306 {
1307 #if EXTRA_CHECKS
1308   unsigned int i;
1309
1310   if (uri->type == GNUNET_FS_URI_KSK)
1311   {
1312     for (i=0;i < uri->data.ksk.keywordCount; i++)
1313       GNUNET_assert (uri->data.ksk.keywords[i] != NULL);
1314   }
1315 #endif
1316   return uri->type == GNUNET_FS_URI_KSK;
1317 }
1318
1319
1320 /**
1321  * Is this a file (or directory) URI?
1322  *
1323  * @param uri the uri to check
1324  * @return #GNUNET_YES if this is a CHK uri
1325  */
1326 int
1327 GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri)
1328 {
1329   return uri->type == GNUNET_FS_URI_CHK;
1330 }
1331
1332
1333 /**
1334  * What is the size of the file that this URI
1335  * refers to?
1336  *
1337  * @param uri the CHK URI to inspect
1338  * @return size of the file as specified in the CHK URI
1339  */
1340 uint64_t
1341 GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri * uri)
1342 {
1343   switch (uri->type)
1344   {
1345   case GNUNET_FS_URI_CHK:
1346     return GNUNET_ntohll (uri->data.chk.file_length);
1347   case GNUNET_FS_URI_LOC:
1348     return GNUNET_ntohll (uri->data.loc.fi.file_length);
1349   default:
1350     GNUNET_assert (0);
1351   }
1352   return 0;                     /* unreachable */
1353 }
1354
1355
1356 /**
1357  * Is this a location URI?
1358  *
1359  * @param uri the uri to check
1360  * @return #GNUNET_YES if this is a LOC uri
1361  */
1362 int
1363 GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri)
1364 {
1365   return uri->type == GNUNET_FS_URI_LOC;
1366 }
1367
1368
1369 /**
1370  * Add a keyword as non-mandatory (with ' '-prefix) to the
1371  * given keyword list at offset 'index'.  The array is
1372  * guaranteed to be long enough.
1373  *
1374  * @param s keyword to add
1375  * @param array array to add the keyword to
1376  * @param index offset where to add the keyword
1377  */
1378 static void
1379 insert_non_mandatory_keyword (const char *s,
1380                               char **array,
1381                               int index)
1382 {
1383   char *nkword;
1384
1385   GNUNET_asprintf (&nkword,
1386                    " %s", /* space to mark as 'non mandatory' */
1387                    s);
1388   array[index] = nkword;
1389 }
1390
1391
1392 /**
1393  * Test if the given keyword @a s is already present in the
1394  * given array, ignoring the '+'-mandatory prefix in the array.
1395  *
1396  * @param s keyword to test
1397  * @param array keywords to test against, with ' ' or '+' prefix to ignore
1398  * @param array_length length of the @a array
1399  * @return #GNUNET_YES if the keyword exists, #GNUNET_NO if not
1400  */
1401 static int
1402 find_duplicate (const char *s,
1403                 const char **array,
1404                 int array_length)
1405 {
1406   int j;
1407
1408   for (j = array_length - 1; j >= 0; j--)
1409     if (0 == strcmp (&array[j][1], s))
1410       return GNUNET_YES;
1411   return GNUNET_NO;
1412 }
1413
1414
1415 /**
1416  * FIXME: comment
1417  */
1418 static char *
1419 normalize_metadata (enum EXTRACTOR_MetaFormat format,
1420                     const char *data,
1421                     size_t data_len)
1422 {
1423   uint8_t *free_str = NULL;
1424   uint8_t *str_to_normalize = (uint8_t *) data;
1425   uint8_t *normalized;
1426   size_t r_len;
1427   if (str_to_normalize == NULL)
1428     return NULL;
1429   /* Don't trust libextractor */
1430   if (format == EXTRACTOR_METAFORMAT_UTF8)
1431   {
1432     free_str = (uint8_t *) u8_check ((const uint8_t *) data, data_len);
1433     if (free_str == NULL)
1434       free_str = NULL;
1435     else
1436       format = EXTRACTOR_METAFORMAT_C_STRING;
1437   }
1438   if (format == EXTRACTOR_METAFORMAT_C_STRING)
1439   {
1440     free_str = u8_strconv_from_encoding (data, locale_charset (), iconveh_escape_sequence);
1441     if (free_str == NULL)
1442       return NULL;
1443   }
1444
1445   normalized = u8_tolower (str_to_normalize, strlen ((char *) str_to_normalize), NULL, UNINORM_NFD, NULL, &r_len);
1446   /* free_str is allocated by libunistring internally, use free() */
1447   if (free_str != NULL)
1448     free (free_str);
1449   if (normalized != NULL)
1450   {
1451     /* u8_tolower allocates a non-NULL-terminated string! */
1452     free_str = GNUNET_malloc (r_len + 1);
1453     memcpy (free_str, normalized, r_len);
1454     free_str[r_len] = '\0';
1455     free (normalized);
1456     normalized = free_str;
1457   }
1458   return (char *) normalized;
1459 }
1460
1461
1462 /**
1463  * Counts the number of UTF-8 characters (not bytes) in the string,
1464  * returns that count.
1465  */
1466 static size_t
1467 u8_strcount (const uint8_t *s)
1468 {
1469   size_t count;
1470   ucs4_t c;
1471   GNUNET_assert (s != NULL);
1472   if (s[0] == 0)
1473     return 0;
1474   for (count = 0; s != NULL; count++)
1475     s = u8_next (&c, s);
1476   return count - 1;
1477 }
1478
1479
1480 /**
1481  * Break the filename up by matching [], () and {} pairs to make
1482  * keywords. In case of nesting parentheses only the inner pair counts.
1483  * You can't escape parentheses to scan something like "[blah\{foo]" to
1484  * make a "blah{foo" keyword, this function is only a heuristic!
1485  *
1486  * @param s string to break down.
1487  * @param array array to fill with enclosed tokens. If NULL, then tokens
1488  *        are only counted.
1489  * @param index index at which to start filling the array (entries prior
1490  *        to it are used to check for duplicates). ignored if @a array == NULL.
1491  * @return number of tokens counted (including duplicates), or number of
1492  *         tokens extracted (excluding duplicates). 0 if there are no
1493  *         matching parens in the string (when counting), or when all tokens
1494  *         were duplicates (when extracting).
1495  */
1496 static int
1497 get_keywords_from_parens (const char *s,
1498                           char **array,
1499                           int index)
1500 {
1501   int count = 0;
1502   char *open_paren;
1503   char *close_paren;
1504   char *ss;
1505   char tmp;
1506
1507   if (NULL == s)
1508     return 0;
1509   ss = GNUNET_strdup (s);
1510   open_paren = ss - 1;
1511   while (NULL != (open_paren = strpbrk (open_paren + 1, "[{(")))
1512   {
1513     int match = 0;
1514
1515     close_paren = strpbrk (open_paren + 1, "]})");
1516     if (NULL == close_paren)
1517       continue;
1518     switch (open_paren[0])
1519     {
1520     case '[':
1521       if (']' == close_paren[0])
1522         match = 1;
1523       break;
1524     case '{':
1525       if ('}' == close_paren[0])
1526         match = 1;
1527       break;
1528     case '(':
1529       if (')' == close_paren[0])
1530         match = 1;
1531       break;
1532     default:
1533       break;
1534     }
1535     if (match && (close_paren - open_paren > 1))
1536     {
1537       tmp = close_paren[0];
1538       close_paren[0] = '\0';
1539       /* Keywords must be at least 3 characters long */
1540       if (u8_strcount ((const uint8_t *) &open_paren[1]) <= 2)
1541       {
1542         close_paren[0] = tmp;
1543         continue;
1544       }
1545       if (NULL != array)
1546       {
1547         char *normalized;
1548         if (GNUNET_NO == find_duplicate ((const char *) &open_paren[1],
1549             (const char **) array, index + count))
1550         {
1551           insert_non_mandatory_keyword ((const char *) &open_paren[1], array,
1552                                         index + count);
1553           count++;
1554         }
1555         normalized = normalize_metadata (EXTRACTOR_METAFORMAT_UTF8,
1556             &open_paren[1], close_paren - &open_paren[1]);
1557         if (normalized != NULL)
1558         {
1559           if (GNUNET_NO == find_duplicate ((const char *) normalized,
1560               (const char **) array, index + count))
1561           {
1562             insert_non_mandatory_keyword ((const char *) normalized, array,
1563                                           index + count);
1564             count++;
1565           }
1566           GNUNET_free (normalized);
1567         }
1568       }
1569       else
1570         count++;
1571       close_paren[0] = tmp;
1572     }
1573   }
1574   GNUNET_free (ss);
1575   return count;
1576 }
1577
1578
1579 /**
1580  * Where to break up keywords
1581  */
1582 #define TOKENS "_. /-!?#&+@\"\'\\;:,()[]{}$<>|"
1583
1584 /**
1585  * Break the filename up by TOKENS to make
1586  * keywords.
1587  *
1588  * @param s string to break down.
1589  * @param array array to fill with tokens. If NULL, then tokens are only
1590  *        counted.
1591  * @param index index at which to start filling the array (entries prior
1592  *        to it are used to check for duplicates). ignored if @a array == NULL.
1593  * @return number of tokens (>1) counted (including duplicates), or number of
1594  *         tokens extracted (excluding duplicates). 0 if there are no
1595  *         separators in the string (when counting), or when all tokens were
1596  *         duplicates (when extracting).
1597  */
1598 static int
1599 get_keywords_from_tokens (const char *s,
1600                           char **array,
1601                           int index)
1602 {
1603   char *p;
1604   char *ss;
1605   int seps = 0;
1606
1607   ss = GNUNET_strdup (s);
1608   for (p = strtok (ss, TOKENS); p != NULL; p = strtok (NULL, TOKENS))
1609   {
1610     /* Keywords must be at least 3 characters long */
1611     if (u8_strcount ((const uint8_t *) p) <= 2)
1612       continue;
1613     if (NULL != array)
1614     {
1615       char *normalized;
1616       if (GNUNET_NO == find_duplicate (p, (const char **) array, index + seps))
1617       {
1618         insert_non_mandatory_keyword (p, array,
1619                                       index + seps);
1620         seps++;
1621       }
1622       normalized = normalize_metadata (EXTRACTOR_METAFORMAT_UTF8,
1623           p, strlen (p));
1624       if (normalized != NULL)
1625       {
1626         if (GNUNET_NO == find_duplicate ((const char *) normalized,
1627             (const char **) array, index + seps))
1628         {
1629           insert_non_mandatory_keyword ((const char *) normalized, array,
1630                                   index + seps);
1631           seps++;
1632         }
1633         GNUNET_free (normalized);
1634       }
1635     }
1636     else
1637       seps++;
1638   }
1639   GNUNET_free (ss);
1640   return seps;
1641 }
1642 #undef TOKENS
1643
1644
1645 /**
1646  * Function called on each value in the meta data.
1647  * Adds it to the URI.
1648  *
1649  * @param cls URI to update
1650  * @param plugin_name name of the plugin that produced this value;
1651  *        special values can be used (i.e. '&lt;zlib&gt;' for zlib being
1652  *        used in the main libextractor library and yielding
1653  *        meta data).
1654  * @param type libextractor-type describing the meta data
1655  * @param format basic format information about data
1656  * @param data_mime_type mime-type of data (not of the original file);
1657  *        can be NULL (if mime-type is not known)
1658  * @param data actual meta-data found
1659  * @param data_len number of bytes in @a data
1660  * @return 0 (always)
1661  */
1662 static int
1663 gather_uri_data (void *cls, const char *plugin_name,
1664                  enum EXTRACTOR_MetaType type,
1665                  enum EXTRACTOR_MetaFormat format,
1666                  const char *data_mime_type,
1667                  const char *data,
1668                  size_t data_len)
1669 {
1670   struct GNUNET_FS_Uri *uri = cls;
1671   char *normalized_data;
1672   const char *sep;
1673
1674   if ((format != EXTRACTOR_METAFORMAT_UTF8) &&
1675       (format != EXTRACTOR_METAFORMAT_C_STRING))
1676     return 0;
1677   /* Keywords must be at least 3 characters long
1678    * If given non-utf8 string it will, most likely, find it to be invalid,
1679    * and will return the length of its valid part, skipping the keyword.
1680    * If it does - fix the extractor, not this check!
1681    */
1682   if (u8_strcount ((const uint8_t *) data) <= 2)
1683     return 0;
1684   if ( (EXTRACTOR_METATYPE_MIMETYPE == type) &&
1685        (NULL != (sep = memchr (data, '/', data_len))) &&
1686        (sep != data) )
1687   {
1688     char *xtra;
1689
1690     GNUNET_asprintf (&xtra,
1691                      "mimetype:%.*s",
1692                      (int) (sep - data),
1693                      data);
1694     if (! find_duplicate (xtra,
1695                           (const char **) uri->data.ksk.keywords,
1696                           uri->data.ksk.keywordCount))
1697     {
1698       insert_non_mandatory_keyword (xtra,
1699                                     uri->data.ksk.keywords,
1700                                     uri->data.ksk.keywordCount);
1701       uri->data.ksk.keywordCount++;
1702     }
1703     GNUNET_free (xtra);
1704   }
1705
1706   normalized_data = normalize_metadata (format, data, data_len);
1707   if (! find_duplicate (data,
1708                         (const char **) uri->data.ksk.keywords,
1709                         uri->data.ksk.keywordCount))
1710   {
1711     insert_non_mandatory_keyword (data,
1712                                   uri->data.ksk.keywords, uri->data.ksk.keywordCount);
1713     uri->data.ksk.keywordCount++;
1714   }
1715   if (NULL != normalized_data)
1716     {
1717     if (! find_duplicate (normalized_data,
1718                           (const char **) uri->data.ksk.keywords,
1719                           uri->data.ksk.keywordCount))
1720     {
1721       insert_non_mandatory_keyword (normalized_data,
1722                                     uri->data.ksk.keywords, uri->data.ksk.keywordCount);
1723       uri->data.ksk.keywordCount++;
1724     }
1725     GNUNET_free (normalized_data);
1726   }
1727   return 0;
1728 }
1729
1730
1731 /**
1732  * Construct a keyword-URI from meta-data (take all entries
1733  * in the meta-data and construct one large keyword URI
1734  * that lists all keywords that can be found in the meta-data).
1735  *
1736  * @param md metadata to use
1737  * @return NULL on error, otherwise a KSK URI
1738  */
1739 struct GNUNET_FS_Uri *
1740 GNUNET_FS_uri_ksk_create_from_meta_data (const struct GNUNET_CONTAINER_MetaData *md)
1741 {
1742   struct GNUNET_FS_Uri *ret;
1743   char *filename;
1744   char *full_name = NULL;
1745   char *ss;
1746   int ent;
1747   int tok_keywords = 0;
1748   int paren_keywords = 0;
1749
1750   if (NULL == md)
1751     return NULL;
1752   ret = GNUNET_new (struct GNUNET_FS_Uri);
1753   ret->type = GNUNET_FS_URI_KSK;
1754   ent = GNUNET_CONTAINER_meta_data_iterate (md, NULL, NULL);
1755   if (ent > 0)
1756   {
1757     full_name = GNUNET_CONTAINER_meta_data_get_first_by_types (md,
1758         EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, -1);
1759     if (NULL != full_name)
1760     {
1761       filename = full_name;
1762       while (NULL != (ss = strstr (filename, DIR_SEPARATOR_STR)))
1763         filename = ss + 1;
1764       tok_keywords = get_keywords_from_tokens (filename, NULL, 0);
1765       paren_keywords = get_keywords_from_parens (filename, NULL, 0);
1766     }
1767     /* x3 because there might be a normalized variant of every keyword,
1768        plus theoretically one more for mime... */
1769     ret->data.ksk.keywords = GNUNET_malloc
1770       (sizeof (char *) * (ent + tok_keywords + paren_keywords) * 3);
1771     GNUNET_CONTAINER_meta_data_iterate (md, &gather_uri_data, ret);
1772   }
1773   if (tok_keywords > 0)
1774     ret->data.ksk.keywordCount += get_keywords_from_tokens (filename,
1775                                                             ret->data.ksk.keywords,
1776                                                             ret->data.ksk.keywordCount);
1777   if (paren_keywords > 0)
1778     ret->data.ksk.keywordCount += get_keywords_from_parens (filename,
1779                                                             ret->data.ksk.keywords,
1780                                                             ret->data.ksk.keywordCount);
1781   if (ent > 0)
1782     GNUNET_free_non_null (full_name);
1783   return ret;
1784 }
1785
1786
1787 /**
1788  * In URI-encoding, does the given character
1789  * need to be encoded using %-encoding?
1790  */
1791 static int
1792 needs_percent (char c)
1793 {
1794   return (!
1795           ((isalnum ((unsigned char) c)) || (c == '-') || (c == '_') ||
1796            (c == '.') || (c == '~')));
1797 }
1798
1799
1800 /**
1801  * Convert a KSK URI to a string.
1802  *
1803  * @param uri the URI to convert
1804  * @return NULL on error (i.e. keywordCount == 0)
1805  */
1806 static char *
1807 uri_ksk_to_string (const struct GNUNET_FS_Uri *uri)
1808 {
1809   char **keywords;
1810   unsigned int keywordCount;
1811   size_t n;
1812   char *ret;
1813   unsigned int i;
1814   unsigned int j;
1815   unsigned int wpos;
1816   size_t slen;
1817   const char *keyword;
1818
1819   if (uri->type != GNUNET_FS_URI_KSK)
1820     return NULL;
1821   keywords = uri->data.ksk.keywords;
1822   keywordCount = uri->data.ksk.keywordCount;
1823   n = keywordCount + strlen (GNUNET_FS_URI_PREFIX) +
1824       strlen (GNUNET_FS_URI_KSK_INFIX) + 1;
1825   for (i = 0; i < keywordCount; i++)
1826   {
1827     keyword = keywords[i];
1828     slen = strlen (keyword);
1829     n += slen;
1830     for (j = 0; j < slen; j++)
1831     {
1832       if ((j == 0) && (keyword[j] == ' '))
1833       {
1834         n--;
1835         continue;               /* skip leading space */
1836       }
1837       if (needs_percent (keyword[j]))
1838         n += 2;                 /* will use %-encoding */
1839     }
1840   }
1841   ret = GNUNET_malloc (n);
1842   strcpy (ret, GNUNET_FS_URI_PREFIX);
1843   strcat (ret, GNUNET_FS_URI_KSK_INFIX);
1844   wpos = strlen (ret);
1845   for (i = 0; i < keywordCount; i++)
1846   {
1847     keyword = keywords[i];
1848     slen = strlen (keyword);
1849     for (j = 0; j < slen; j++)
1850     {
1851       if ((j == 0) && (keyword[j] == ' '))
1852         continue;               /* skip leading space */
1853       if (needs_percent (keyword[j]))
1854       {
1855         sprintf (&ret[wpos], "%%%02X", (unsigned char) keyword[j]);
1856         wpos += 3;
1857       }
1858       else
1859       {
1860         ret[wpos++] = keyword[j];
1861       }
1862     }
1863     if (i != keywordCount - 1)
1864       ret[wpos++] = '+';
1865   }
1866   return ret;
1867 }
1868
1869
1870 /**
1871  * Convert SKS URI to a string.
1872  *
1873  * @param uri sks uri to convert
1874  * @return NULL on error
1875  */
1876 static char *
1877 uri_sks_to_string (const struct GNUNET_FS_Uri *uri)
1878 {
1879   char *ret;
1880   char buf[1024];
1881
1882   if (GNUNET_FS_URI_SKS != uri->type)
1883     return NULL;
1884   ret = GNUNET_STRINGS_data_to_string (&uri->data.sks.ns,
1885                                        sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey),
1886                                        buf,
1887                                        sizeof (buf));
1888   GNUNET_assert (NULL != ret);
1889   ret[0] = '\0';
1890   GNUNET_asprintf (&ret, "%s%s%s/%s", GNUNET_FS_URI_PREFIX,
1891                    GNUNET_FS_URI_SKS_INFIX, buf,
1892                    uri->data.sks.identifier);
1893   return ret;
1894 }
1895
1896
1897 /**
1898  * Convert a CHK URI to a string.
1899  *
1900  * @param uri chk uri to convert
1901  * @return NULL on error
1902  */
1903 static char *
1904 uri_chk_to_string (const struct GNUNET_FS_Uri *uri)
1905 {
1906   const struct FileIdentifier *fi;
1907   char *ret;
1908   struct GNUNET_CRYPTO_HashAsciiEncoded keyhash;
1909   struct GNUNET_CRYPTO_HashAsciiEncoded queryhash;
1910
1911   if (uri->type != GNUNET_FS_URI_CHK)
1912     return NULL;
1913   fi = &uri->data.chk;
1914   GNUNET_CRYPTO_hash_to_enc (&fi->chk.key, &keyhash);
1915   GNUNET_CRYPTO_hash_to_enc (&fi->chk.query, &queryhash);
1916
1917   GNUNET_asprintf (&ret, "%s%s%s.%s.%llu", GNUNET_FS_URI_PREFIX,
1918                    GNUNET_FS_URI_CHK_INFIX, (const char *) &keyhash,
1919                    (const char *) &queryhash, GNUNET_ntohll (fi->file_length));
1920   return ret;
1921 }
1922
1923
1924 /**
1925  * Convert a LOC URI to a string.
1926  *
1927  * @param uri loc uri to convert
1928  * @return NULL on error
1929  */
1930 static char *
1931 uri_loc_to_string (const struct GNUNET_FS_Uri *uri)
1932 {
1933   char *ret;
1934   struct GNUNET_CRYPTO_HashAsciiEncoded keyhash;
1935   struct GNUNET_CRYPTO_HashAsciiEncoded queryhash;
1936   char *peer_id;
1937   char peer_sig[SIGNATURE_ASCII_LENGTH + 1];
1938
1939   GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.key, &keyhash);
1940   GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.query, &queryhash);
1941   peer_id =
1942     GNUNET_CRYPTO_eddsa_public_key_to_string (&uri->data.loc.peer.public_key);
1943   GNUNET_assert (NULL !=
1944                  GNUNET_STRINGS_data_to_string (&uri->data.loc.contentSignature,
1945                                                 sizeof (struct GNUNET_CRYPTO_EddsaSignature),
1946                                                 peer_sig,
1947                                                 sizeof (peer_sig)));
1948   GNUNET_asprintf (&ret,
1949                    "%s%s%s.%s.%llu.%s.%s.%llu", GNUNET_FS_URI_PREFIX,
1950                    GNUNET_FS_URI_LOC_INFIX, (const char *) &keyhash,
1951                    (const char *) &queryhash,
1952                    (unsigned long long) GNUNET_ntohll (uri->data.loc.
1953                                                        fi.file_length),
1954                    peer_id,
1955                    peer_sig,
1956                    (unsigned long long) uri->data.loc.expirationTime.abs_value_us / 1000000LL);
1957   GNUNET_free (peer_id);
1958   return ret;
1959 }
1960
1961
1962 /**
1963  * Convert a URI to a UTF-8 String.
1964  *
1965  * @param uri uri to convert to a string
1966  * @return the UTF-8 string
1967  */
1968 char *
1969 GNUNET_FS_uri_to_string (const struct GNUNET_FS_Uri *uri)
1970 {
1971   if (uri == NULL)
1972   {
1973     GNUNET_break (0);
1974     return NULL;
1975   }
1976   switch (uri->type)
1977   {
1978   case GNUNET_FS_URI_KSK:
1979     return uri_ksk_to_string (uri);
1980   case GNUNET_FS_URI_SKS:
1981     return uri_sks_to_string (uri);
1982   case GNUNET_FS_URI_CHK:
1983     return uri_chk_to_string (uri);
1984   case GNUNET_FS_URI_LOC:
1985     return uri_loc_to_string (uri);
1986   default:
1987     GNUNET_break (0);
1988     return NULL;
1989   }
1990 }
1991
1992 /* end of fs_uri.c */