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