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