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