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