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