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