61fb7d61df382afdd0686dc2fdeebceeaaa59323
[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 2, 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) + 1) ||
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   pos = 0;
496   for (pos = 0; pos < size; pos++)
497     {
498       while (hbits < 8)
499         {
500           bits |= (c2v (input[len++]) << hbits);
501           hbits += 6;
502         }
503       (((unsigned char *) data)[pos]) = (unsigned char) bits;
504       bits >>= 8;
505       hbits -= 8;
506     }
507   return len;
508 }
509
510
511 /**
512  * Structure that defines how the
513  * contents of a location URI must be
514  * assembled in memory to create or
515  * verify the signature of a location
516  * URI.
517  */
518 struct LocUriAssembly 
519 {
520   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
521
522   struct GNUNET_TIME_AbsoluteNBO exptime;
523
524   struct FileIdentifier fi;
525   
526   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded peer;
527
528 };
529
530
531 /**
532  * Parse a LOC URI.
533  * Also verifies validity of the location URI.
534  *
535  * @param s an uri string
536  * @param emsg where to store the parser error message (if any)
537  * @return NULL on error, valid LOC URI otherwise
538  */
539 static struct GNUNET_FS_Uri *
540 uri_loc_parse (const char *s, char **emsg)
541 {
542   struct GNUNET_FS_Uri *uri;
543   char h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)];
544   char h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)];
545   unsigned int pos;
546   unsigned int npos;
547   unsigned long long exptime;
548   unsigned long long flen;
549   struct GNUNET_TIME_Absolute et;
550   struct GNUNET_CRYPTO_RsaSignature sig;
551   struct LocUriAssembly ass;
552   int ret;
553   size_t slen;
554
555   GNUNET_assert (s != NULL);
556   slen = strlen (s);
557   pos = strlen (GNUNET_FS_URI_PREFIX GNUNET_FS_URI_LOC_INFIX);
558   if ( (slen < pos + 2 * sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) ||
559        (0 != strncmp (s, GNUNET_FS_URI_PREFIX GNUNET_FS_URI_LOC_INFIX, 
560                       pos) ) )
561     return NULL; /* not an SKS URI */
562   if ( (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') ||
563        (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.') )
564     {
565       *emsg = GNUNET_strdup (_("SKS URI malformed"));
566       return NULL;
567     }
568   memcpy (h1,
569           &s[pos], 
570           sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded));
571   h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)-1] = '\0';
572   memcpy (h2,
573           &s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)],
574           sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded));
575   h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)-1] = '\0';
576   
577   if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h1,
578                                                     &ass.fi.chk.key)) ||
579       (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h2,
580                                                     &ass.fi.chk.query)) ||
581       (1 != SSCANF (&s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2],
582                     "%llu", 
583                     &flen)) )
584     {
585       *emsg = GNUNET_strdup (_("SKS URI malformed"));
586       return NULL;
587     }
588   ass.fi.file_length = GNUNET_htonll (flen);
589
590   npos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2;
591   while ((s[npos] != '\0') && (s[npos] != '.'))
592     npos++;
593   if (s[npos] == '\0')
594     {
595       *emsg = GNUNET_strdup (_("SKS URI malformed"));
596       goto ERR;
597     }
598   npos++;
599   ret = enc2bin (&s[npos], 
600                  &ass.peer,
601                  sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
602   if (ret == -1)
603     {
604       *emsg = GNUNET_strdup (_("SKS URI malformed (could not decode public key)"));
605       goto ERR;
606     }
607   npos += ret;
608   if (s[npos++] != '.')
609     {
610       *emsg = GNUNET_strdup (_("SKS URI malformed (could not find signature)"));
611       goto ERR;
612     }
613   ret = enc2bin (&s[npos],
614                  &sig,
615                  sizeof (struct GNUNET_CRYPTO_RsaSignature));
616   if (ret == -1)
617     {
618       *emsg = GNUNET_strdup (_("SKS URI malformed (could not decode signature)"));
619       goto ERR;
620     }
621     npos += ret;
622   if (s[npos++] != '.')
623     {
624       *emsg = GNUNET_strdup (_("SKS URI malformed"));
625       goto ERR;
626     }
627   if (1 != SSCANF (&s[npos], "%llu", &exptime))
628     {
629       *emsg = GNUNET_strdup (_("SKS URI malformed (could not parse expiration time)"));
630       goto ERR;
631     }
632   ass.purpose.size = htonl(sizeof(struct LocUriAssembly));
633   ass.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT);
634   et.value = exptime;
635   ass.exptime = GNUNET_TIME_absolute_hton (et);
636   if (GNUNET_OK != 
637       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT,
638                                 &ass.purpose,
639                                 &sig,
640                                 &ass.peer))
641     {
642       *emsg = GNUNET_strdup (_("SKS URI malformed (signature failed validation)"));
643       goto ERR;
644     }
645   uri = GNUNET_malloc (sizeof(struct GNUNET_FS_Uri));
646   uri->type = loc;
647   uri->data.loc.fi = ass.fi;
648   uri->data.loc.peer = ass.peer;
649   uri->data.loc.expirationTime = et;
650   uri->data.loc.contentSignature = sig;
651
652   return uri;
653 ERR:
654   return NULL;
655 }
656
657
658 /**
659  * Convert a UTF-8 String to a URI.
660  *
661  * @param uri string to parse
662  * @param emsg where to store the parser error message (if any)
663  * @return NULL on error
664  */
665 struct GNUNET_FS_Uri *
666 GNUNET_FS_uri_parse (const char *uri,
667                      char **emsg)
668 {
669   struct GNUNET_FS_Uri *ret;
670   char *msg;
671
672   if (NULL == emsg)
673     emsg = &msg;
674   *emsg = NULL;
675   if ( (NULL != (ret = uri_chk_parse (uri, emsg))) ||
676        (NULL != (ret = uri_ksk_parse (uri, emsg))) ||
677        (NULL != (ret = uri_sks_parse (uri, emsg))) ||
678        (NULL != (ret = uri_loc_parse (uri, emsg))) )
679     return ret;
680   if (NULL == *emsg)
681     *emsg = GNUNET_strdup (_("Unrecognized URI type"));
682   if (emsg == &msg)
683     GNUNET_free (msg);
684   return NULL;
685 }
686
687
688 /**
689  * Free URI.
690  *
691  * @param uri uri to free
692  */
693 void 
694 GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri)
695 {
696   unsigned int i;
697
698   GNUNET_assert (uri != NULL);
699   switch (uri->type)
700     {
701     case ksk:
702       for (i = 0; i < uri->data.ksk.keywordCount; i++)
703         GNUNET_free (uri->data.ksk.keywords[i]);
704       GNUNET_array_grow (uri->data.ksk.keywords, uri->data.ksk.keywordCount,
705                          0);
706       break;
707     case sks:
708       GNUNET_free (uri->data.sks.identifier);
709       break;
710     case loc:
711       break;
712     default:
713       /* do nothing */
714       break;
715     }
716   GNUNET_free (uri);
717 }
718
719 /**
720  * How many keywords are ANDed in this keyword URI?
721  *
722  * @param uri ksk uri to get the number of keywords from
723  * @return 0 if this is not a keyword URI
724  */
725 unsigned int 
726 GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri)
727 {
728   if (uri->type != ksk)
729     return 0;
730   return uri->data.ksk.keywordCount;
731 }
732
733
734 /**
735  * Iterate over all keywords in this keyword URI.
736  *
737  * @param uri ksk uri to get the keywords from
738  * @param iterator function to call on each keyword
739  * @param iterator_cls closure for iterator
740  * @return -1 if this is not a keyword URI, otherwise number of
741  *   keywords iterated over until iterator aborted
742  */
743 int 
744 GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri,
745                                 GNUNET_FS_KeywordIterator iterator, 
746                                 void *iterator_cls)
747 {
748   unsigned int i;
749   char *keyword;
750
751   if (uri->type != ksk)
752     return -1;
753   if (iterator == NULL)
754     return uri->data.ksk.keywordCount;
755   for (i = 0; i < uri->data.ksk.keywordCount; i++)
756     {
757       keyword = uri->data.ksk.keywords[i];
758       /* first character of keyword indicates
759          if it is mandatory or not */
760       if (GNUNET_OK != iterator (iterator_cls,
761                                  &keyword[1],
762                                  keyword[0] == '+'))
763         return i;
764     }
765   return i;
766 }
767
768
769 /**
770  * Obtain the identity of the peer offering the data
771  *
772  * @param uri the location URI to inspect
773  * @param peer where to store the identify of the peer (presumably) offering the content
774  * @return GNUNET_SYSERR if this is not a location URI, otherwise GNUNET_OK
775  */
776 int
777 GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri,
778                                      struct GNUNET_PeerIdentity * peer)
779 {
780   if (uri->type != loc)
781     return GNUNET_SYSERR;
782   GNUNET_CRYPTO_hash (&uri->data.loc.peer,
783                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
784                       &peer->hashPubKey);
785   return GNUNET_OK;
786 }
787
788
789 /**
790  * Obtain the URI of the content itself.
791  *
792  * @param uri location URI to get the content URI from
793  * @return NULL if argument is not a location URI
794  */
795 struct GNUNET_FS_Uri *
796 GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri)
797 {
798   struct GNUNET_FS_Uri *ret;
799
800   if (uri->type != loc)
801     return NULL;
802   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
803   ret->type = chk;
804   ret->data.chk = uri->data.loc.fi;
805   return ret;
806 }
807
808
809 /**
810  * Construct a location URI (this peer will be used for the location).
811  *
812  * @param baseURI content offered by the sender
813  * @param cfg configuration information (used to find our hostkey)
814  * @param expiration_time how long will the content be offered?
815  * @return the location URI, NULL on error
816  */
817 struct GNUNET_FS_Uri *
818 GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *baseUri,
819                           struct GNUNET_CONFIGURATION_Handle *cfg,
820                           struct GNUNET_TIME_Absolute expiration_time)
821 {
822   struct GNUNET_FS_Uri *uri;
823   struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;  
824   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
825   char *keyfile;
826   struct LocUriAssembly ass;
827
828   if (baseUri->type != chk)
829     return NULL;
830   if (GNUNET_OK !=
831       GNUNET_CONFIGURATION_get_value_filename (cfg,
832                                                "GNUNETD",
833                                                "HOSTKEY", &keyfile))
834     {
835       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
836                   _
837                   ("Lacking key configuration settings.\n"));
838       return NULL;
839     }
840   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
841   if (my_private_key == NULL)
842     {
843       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
844                   _("Could not access hostkey file `%s'.\n"),
845                   keyfile);
846       GNUNET_free (keyfile);
847       return NULL;
848     }
849   GNUNET_free (keyfile);
850   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
851   ass.purpose.size = htonl(sizeof(struct LocUriAssembly));
852   ass.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT);
853   ass.exptime = GNUNET_TIME_absolute_hton (expiration_time);
854   ass.fi = baseUri->data.chk;
855   ass.peer = my_public_key;
856   uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
857   uri->type = loc;
858   uri->data.loc.fi = baseUri->data.chk;
859   uri->data.loc.expirationTime = expiration_time;
860   uri->data.loc.peer = my_public_key;
861   GNUNET_assert (GNUNET_OK ==
862                  GNUNET_CRYPTO_rsa_sign (my_private_key,
863                                          &ass.purpose,
864                                          &uri->data.loc.contentSignature));
865   GNUNET_CRYPTO_rsa_key_free (my_private_key);
866   return uri;
867 }
868
869
870 /**
871  * Canonicalize a keyword.
872  * 
873  * @param in input string (the keyword)
874  * @return canonicalized keyword
875  */
876 static char *
877 canonicalize_keyword (const char *in)
878 {
879   char *ret;
880   char *wpos;
881   const char *rpos;
882
883   ret = GNUNET_strdup (in);
884   wpos = ret;
885   rpos = in;
886   while ('\0' != *rpos)
887     {
888       switch (tolower(*rpos))
889         {
890         case 'a':
891         case 'e':
892         case 'i':
893         case 'o':
894         case 'u':
895         case ' ':
896         case '\t':
897         case '\n':
898         case '\r':
899           /* skip characters listed above */
900           rpos++;
901           break;
902         case 'b':
903         case 'c':
904         case 'd':
905         case 'f':
906         case 'g':
907         case 'h':
908         case 'j':
909         case 'k':
910         case 'l':
911         case 'm':
912         case 'n':
913         case 'p':
914         case 'r':
915         case 's':
916         case 't':
917         case 'v':
918         case 'w':
919         case 'x':
920         case 'y':
921         case 'z':
922           /* convert characters listed above to lower case */
923           *wpos = tolower(*rpos);
924           wpos++;
925         case '!':
926         case '.':
927         case '?':
928         case '-':
929           /* keep characters listed above without changes */
930           *wpos = *rpos;
931           wpos++;
932         default:
933           /* replace characters listed above with '_' */
934           *wpos = '_';
935           wpos++;
936         }
937       rpos++;
938     }
939   return ret;
940 }
941
942
943 /**
944  * Canonicalize keyword URI.  Performs operations such
945  * as decapitalization and removal of certain characters.
946  * (useful for search).
947  *
948  * @param uri the URI to canonicalize 
949  * @return canonicalized version of the URI, NULL on error
950  */
951 struct GNUNET_FS_Uri *
952 GNUNET_FS_uri_ksk_canonicalize (const struct GNUNET_FS_Uri *uri)
953 {
954   struct GNUNET_FS_Uri *ret;
955   unsigned int kc;
956   unsigned int i;
957   char **kl;
958
959   kc = uri->data.ksk.keywordCount;
960   kl = GNUNET_malloc (kc*sizeof(char*));
961   for (i=0;i<kc;i++)
962     kl[i] = canonicalize_keyword (uri->data.ksk.keywords[i]);
963   ret = GNUNET_malloc (sizeof(struct GNUNET_FS_Uri));
964   ret->type = ksk;
965   ret->data.ksk.keywordCount = kc;
966   ret->data.ksk.keywords = kl;
967   return ret;
968 }
969
970
971 /**
972  * Merge the sets of keywords from two KSK URIs.
973  * (useful for merging the canonicalized keywords with
974  * the original keywords for sharing).
975  *
976  * @param u1 first uri
977  * @param u2 second uri
978  * @return merged URI, NULL on error
979  */
980 struct GNUNET_FS_Uri *
981 GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1,
982                          const struct GNUNET_FS_Uri *u2)
983 {
984   struct GNUNET_FS_Uri *ret;
985   unsigned int kc;
986   unsigned int i;
987   unsigned int j;
988   int found;
989   const char *kp;
990   char **kl;
991
992   if ( (u1->type != ksk) ||
993        (u2->type != ksk) )
994     {
995       GNUNET_break (0);
996       return NULL;
997     } 
998   kc = u1->data.ksk.keywordCount;
999   kl = GNUNET_malloc ((kc+u2->data.ksk.keywordCount)*sizeof(char*));
1000   for (i=0;i<u1->data.ksk.keywordCount;i++)
1001     kl[i] = GNUNET_strdup (u1->data.ksk.keywords[i]);
1002   for (i=0;i<u2->data.ksk.keywordCount;i++)
1003     {
1004       kp = u2->data.ksk.keywords[i];
1005       found = 0;
1006       for (j=0;j<u1->data.ksk.keywordCount;j++)
1007         if (0 == strcmp(kp + 1,
1008                         kl[j]+1))
1009           {
1010             found = 1;
1011             if (kp[0] == '+')
1012               kl[j][0] = '+';
1013             break;
1014           }
1015       if (0 == found)
1016         kl[kc++] = GNUNET_strdup (kp - 1);
1017     }
1018   ret = GNUNET_malloc (sizeof(struct GNUNET_FS_Uri));
1019   ret->type = ksk;
1020   ret->data.ksk.keywordCount = kc;
1021   ret->data.ksk.keywords = kl;
1022   return ret;
1023 }
1024
1025
1026 /**
1027  * Duplicate URI.
1028  *
1029  * @param uri the URI to duplicate
1030  * @return copy of the URI
1031  */
1032 struct GNUNET_FS_Uri *
1033 GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri)
1034 {
1035   struct GNUNET_FS_Uri *ret;
1036   unsigned int i;
1037
1038   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
1039   memcpy (ret, uri, sizeof (struct GNUNET_FS_Uri));
1040   switch (ret->type)
1041     {
1042     case ksk:
1043       if (ret->data.ksk.keywordCount > 0)
1044         {
1045           ret->data.ksk.keywords
1046             = GNUNET_malloc (ret->data.ksk.keywordCount * sizeof (char *));
1047           for (i = 0; i < ret->data.ksk.keywordCount; i++)
1048             ret->data.ksk.keywords[i] =
1049               GNUNET_strdup (uri->data.ksk.keywords[i]);
1050         }
1051       else
1052         ret->data.ksk.keywords = NULL;  /* just to be sure */
1053       break;
1054     case sks:
1055       ret->data.sks.identifier = GNUNET_strdup (uri->data.sks.identifier);
1056       break;
1057     case loc:
1058       break;
1059     default:
1060       break;
1061     }
1062   return ret;
1063 }
1064
1065
1066 /**
1067  * Create an FS URI from a single user-supplied string of keywords.
1068  * The string is broken up at spaces into individual keywords.
1069  * Keywords that start with "+" are mandatory.  Double-quotes can
1070  * be used to prevent breaking up strings at spaces (and also
1071  * to specify non-mandatory keywords starting with "+").
1072  *
1073  * Keywords must contain a balanced number of double quotes and
1074  * double quotes can not be used in the actual keywords (for
1075  * example, the string '""foo bar""' will be turned into two
1076  * "OR"ed keywords 'foo' and 'bar', not into '"foo bar"'.
1077  *
1078  * @param keywords the keyword string
1079  * @param emsg where to store an error message
1080  * @return an FS URI for the given keywords, NULL
1081  *  if keywords is not legal (i.e. empty).
1082  */
1083 struct GNUNET_FS_Uri *
1084 GNUNET_FS_uri_ksk_create (const char *keywords,
1085                           char **emsg)
1086 {
1087   char **keywordarr;
1088   unsigned int num_Words;
1089   int inWord;
1090   char *pos;
1091   struct GNUNET_FS_Uri *uri;
1092   char *searchString;
1093   int saw_quote;
1094
1095   if (keywords == NULL)
1096     {
1097       GNUNET_break (0);
1098       return NULL;
1099     }
1100   searchString = GNUNET_strdup (keywords);
1101   num_Words = 0;
1102   inWord = 0;
1103   saw_quote = 0;
1104   pos = searchString;
1105   while ('\0' != *pos)
1106     {
1107       if ((saw_quote == 0) && (isspace (*pos)))
1108         {
1109           inWord = 0;
1110         }
1111       else if (0 == inWord)
1112         {
1113           inWord = 1;
1114           ++num_Words;
1115         }
1116       if ('"' == *pos)
1117         saw_quote = (saw_quote + 1) % 2;
1118       pos++;
1119     }
1120   if (num_Words == 0)
1121     {
1122       GNUNET_free (searchString);
1123       *emsg = GNUNET_strdup (_("No keywords specified!\n"));
1124       return NULL;
1125     }
1126   if (saw_quote != 0)
1127     {
1128       GNUNET_free (searchString);
1129       *emsg = GNUNET_strdup (_("Number of double-quotes not balanced!\n"));
1130       return NULL;
1131     }
1132   keywordarr = GNUNET_malloc (num_Words * sizeof (char *));
1133   num_Words = 0;
1134   inWord = 0;
1135   pos = searchString;
1136   while ('\0' != *pos)
1137     {
1138       if ((saw_quote == 0) && (isspace (*pos)))
1139         {
1140           inWord = 0;
1141           *pos = '\0';
1142         }
1143       else if (0 == inWord)
1144         {
1145           keywordarr[num_Words] = pos;
1146           inWord = 1;
1147           ++num_Words;
1148         }
1149       if ('"' == *pos)
1150         saw_quote = (saw_quote + 1) % 2;
1151       pos++;
1152     }
1153   uri =
1154     GNUNET_FS_uri_ksk_create_from_args (num_Words,
1155                                         (const char **) keywordarr);
1156   GNUNET_free (keywordarr);
1157   GNUNET_free (searchString);
1158   return uri;
1159 }
1160
1161
1162 /**
1163  * Create an FS URI from a user-supplied command line of keywords.
1164  * Arguments should start with "+" to indicate mandatory
1165  * keywords.
1166  *
1167  * @param argc number of keywords
1168  * @param argv keywords (double quotes are not required for
1169  *             keywords containing spaces; however, double
1170  *             quotes are required for keywords starting with
1171  *             "+"); there is no mechanism for having double
1172  *             quotes in the actual keywords (if the user
1173  *             did specifically specify double quotes, the
1174  *             caller should convert each double quote
1175  *             into two single quotes).
1176  * @return an FS URI for the given keywords, NULL
1177  *  if keywords is not legal (i.e. empty).
1178  */
1179 struct GNUNET_FS_Uri *
1180 GNUNET_FS_uri_ksk_create_from_args (unsigned int argc,
1181                                     const char **argv)
1182 {
1183   unsigned int i;
1184   struct GNUNET_FS_Uri *uri;
1185   const char *keyword;
1186   char *val;
1187   const char *r;
1188   char *w;
1189   char *emsg;
1190
1191   if (argc == 0)
1192     return NULL;
1193   /* allow URI to be given as one and only keyword and
1194      handle accordingly */
1195   emsg = NULL;
1196   if ( (argc == 1) &&
1197        (strlen(argv[0]) > strlen(GNUNET_FS_URI_PREFIX)) &&
1198        (0 == strncmp(argv[0], GNUNET_FS_URI_PREFIX, strlen(GNUNET_FS_URI_PREFIX)) ) &&
1199        (NULL != (uri = GNUNET_FS_uri_parse(argv[0], &emsg)) ) )
1200     return uri;
1201   GNUNET_free_non_null (emsg);
1202   uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
1203   uri->type = ksk;
1204   uri->data.ksk.keywordCount = argc;
1205   uri->data.ksk.keywords = GNUNET_malloc (argc * sizeof (char *));
1206   for (i = 0; i < argc; i++)
1207     {
1208       keyword = argv[i];
1209       if (keyword[0] == '+')
1210         val = GNUNET_strdup (keyword);
1211       else
1212         GNUNET_asprintf (&val, " %s", keyword);
1213       r = val;
1214       w = val;
1215       while ('\0' != *r)
1216         {
1217           if ('"' == *r)
1218             r++;
1219           else
1220             *(w++) = *(r++);
1221         }
1222       *w = '\0';
1223       uri->data.ksk.keywords[i] = val;
1224     }
1225   return uri;
1226 }
1227
1228
1229 /**
1230  * Test if two URIs are equal.
1231  *
1232  * @param u1 one of the URIs
1233  * @param u2 the other URI
1234  * @return GNUNET_YES if the URIs are equal
1235  */
1236 int 
1237 GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1,
1238                           const struct GNUNET_FS_Uri *u2)
1239 {
1240   int ret;
1241   unsigned int i;
1242   unsigned int j;
1243
1244   GNUNET_assert (u1 != NULL);
1245   GNUNET_assert (u2 != NULL);
1246   if (u1->type != u2->type)
1247     return GNUNET_NO;
1248   switch (u1->type)
1249     {
1250     case chk:
1251       if (0 == memcmp (&u1->data.chk,
1252                        &u2->data.chk,
1253                        sizeof (struct FileIdentifier)))
1254         return GNUNET_YES;
1255       return GNUNET_NO;
1256     case sks:
1257       if ((0 == memcmp (&u1->data.sks.namespace,
1258                         &u2->data.sks.namespace,
1259                         sizeof (GNUNET_HashCode))) &&
1260           (0 == strcmp (u1->data.sks.identifier,
1261                         u2->data.sks.identifier)))
1262
1263         return GNUNET_YES;
1264       return GNUNET_NO;
1265     case ksk:
1266       if (u1->data.ksk.keywordCount != u2->data.ksk.keywordCount)
1267         return GNUNET_NO;
1268       for (i = 0; i < u1->data.ksk.keywordCount; i++)
1269         {
1270           ret = GNUNET_NO;
1271           for (j = 0; j < u2->data.ksk.keywordCount; j++)
1272             {
1273               if (0 == strcmp (u1->data.ksk.keywords[i],
1274                                u2->data.ksk.keywords[j]))
1275                 {
1276                   ret = GNUNET_YES;
1277                   break;
1278                 }
1279             }
1280           if (ret == GNUNET_NO)
1281             return GNUNET_NO;
1282         }
1283       return GNUNET_YES;
1284     case loc:
1285       if (memcmp (&u1->data.loc,
1286                   &u2->data.loc,
1287                   sizeof (struct FileIdentifier) +
1288                   sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1289                   sizeof (struct GNUNET_TIME_Absolute) +
1290                   sizeof (unsigned short) + sizeof (unsigned short)) != 0)
1291         return GNUNET_NO;
1292       return GNUNET_YES;
1293     default:
1294       return GNUNET_NO;
1295     }
1296 }
1297
1298
1299 /**
1300  * Is this a namespace URI?
1301  *
1302  * @param uri the uri to check
1303  * @return GNUNET_YES if this is an SKS uri
1304  */
1305 int
1306 GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri)
1307 {
1308   return uri->type == sks;
1309 }
1310
1311
1312 /**
1313  * Get the ID of a namespace from the given
1314  * namespace URI.
1315  *
1316  * @param uri the uri to get the namespace ID from
1317  * @param nsid where to store the ID of the namespace
1318  * @return GNUNET_OK on success
1319  */
1320 int 
1321 GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri,
1322                                  GNUNET_HashCode * nsid)
1323 {
1324   if (! GNUNET_FS_uri_test_sks (uri))
1325     {
1326       GNUNET_break (0);
1327       return GNUNET_SYSERR;
1328     }
1329   *nsid = uri->data.sks.namespace;
1330   return GNUNET_OK;
1331 }
1332
1333
1334 /**
1335  * Get the content identifier of an SKS URI.
1336  *
1337  * @param uri the sks uri
1338  * @return NULL on error (not a valid SKS URI)
1339  */
1340 char *
1341 GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri)
1342 {
1343   if (!GNUNET_FS_uri_test_sks (uri))
1344     {
1345       GNUNET_break (0);
1346       return NULL;
1347     }
1348   return GNUNET_strdup (uri->data.sks.identifier);
1349 }
1350
1351
1352 /**
1353  * Convert namespace URI to a human readable format
1354  * (using the namespace description, if available).
1355  *
1356  * @param cfg configuration to use
1357  * @param uri SKS uri to convert
1358  * @return NULL on error (not an SKS URI)
1359  */
1360 char *
1361 GNUNET_FS_uri_sks_to_string_fancy (struct GNUNET_CONFIGURATION_Handle *cfg,
1362                                    const struct GNUNET_FS_Uri *uri)
1363 {
1364   char *ret;
1365   char *name;
1366
1367   if (uri->type != sks)
1368     return NULL;
1369   name = GNUNET_PSEUDONYM_id_to_name (cfg, &uri->data.sks.namespace);
1370   if (name == NULL)
1371     return GNUNET_FS_uri_to_string (uri);
1372   GNUNET_asprintf (&ret,
1373                    "%s: %s",
1374                    name,
1375                    uri->data.sks.identifier);
1376   GNUNET_free (name);
1377   return ret;
1378 }
1379
1380
1381 /**
1382  * Is this a keyword URI?
1383  *
1384  * @param uri the uri
1385  * @return GNUNET_YES if this is a KSK uri
1386  */
1387 int 
1388 GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri)
1389 {
1390 #if EXTRA_CHECKS
1391   unsigned int i;
1392
1393   if (uri->type == ksk)
1394     {
1395       for (i = uri->data.ksk.keywordCount - 1; i >= 0; i--)
1396         GNUNET_assert (uri->data.ksk.keywords[i] != NULL);
1397     }
1398 #endif
1399   return uri->type == ksk;
1400 }
1401
1402
1403 /**
1404  * Is this a file (or directory) URI?
1405  *
1406  * @param uri the uri to check
1407  * @return GNUNET_YES if this is a CHK uri
1408  */
1409 int 
1410 GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri)
1411 {
1412   return uri->type == chk;
1413 }
1414
1415
1416 /**
1417  * What is the size of the file that this URI
1418  * refers to?
1419  *
1420  * @param uri the CHK URI to inspect
1421  * @return size of the file as specified in the CHK URI
1422  */
1423 uint64_t 
1424 GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri *uri)
1425 {
1426   switch (uri->type)
1427     {
1428     case chk:
1429       return GNUNET_ntohll (uri->data.chk.file_length);
1430     case loc:
1431       return GNUNET_ntohll (uri->data.loc.fi.file_length);
1432     default:
1433       GNUNET_assert (0);
1434     }
1435   return 0;                     /* unreachable */
1436 }
1437
1438
1439 /**
1440  * Is this a location URI?
1441  *
1442  * @param uri the uri to check
1443  * @return GNUNET_YES if this is a LOC uri
1444  */
1445 int 
1446 GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri)
1447 {
1448   return uri->type == loc;
1449 }
1450
1451
1452 /**
1453  * Function called on each value in the meta data.
1454  * Adds it to the URI.
1455  *
1456  * @param cls URI to update
1457  * @param type type of the meta data
1458  * @param data value of the meta data
1459  * @return GNUNET_OK (always)
1460  */
1461 static int
1462 gather_uri_data (void *cls,
1463                  EXTRACTOR_KeywordType type, 
1464                  const char *data)
1465 {
1466   struct GNUNET_FS_Uri *uri = cls;
1467   char *nkword;
1468   int j;
1469   
1470   for (j = uri->data.ksk.keywordCount - 1; j >= 0; j--)
1471     if (0 == strcmp (&uri->data.ksk.keywords[j][1], data))
1472       return GNUNET_OK;
1473   nkword = GNUNET_malloc (strlen (data) + 2);
1474   strcpy (nkword, " ");         /* not mandatory */
1475   strcat (nkword, data);
1476   uri->data.ksk.keywords[uri->data.ksk.keywordCount++] = nkword;
1477   return GNUNET_OK;
1478 }
1479
1480
1481 /**
1482  * Construct a keyword-URI from meta-data (take all entries
1483  * in the meta-data and construct one large keyword URI
1484  * that lists all keywords that can be found in the meta-data).
1485  * @deprecated
1486  */
1487 struct GNUNET_FS_Uri *
1488 GNUNET_FS_uri_ksk_create_from_meta_data (const struct GNUNET_CONTAINER_MetaData *md)
1489 {
1490   struct GNUNET_FS_Uri *ret;
1491
1492   if (md == NULL)
1493     return NULL;
1494   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
1495   ret->type = ksk;
1496   ret->data.ksk.keywordCount = 0;
1497   ret->data.ksk.keywords = NULL;
1498   ret->data.ksk.keywords
1499     = GNUNET_malloc (sizeof (char *) *
1500                      GNUNET_CONTAINER_meta_data_get_contents (md, NULL, NULL));
1501   GNUNET_CONTAINER_meta_data_get_contents (md, &gather_uri_data, ret);
1502   return ret;
1503
1504 }
1505
1506
1507 /**
1508  * In URI-encoding, does the given character
1509  * need to be encoded using %-encoding?
1510  */
1511 static int
1512 needs_percent (char c)
1513 {
1514   return (!((isalnum (c)) ||
1515             (c == '-') || (c == '_') || (c == '.') || (c == '~')));
1516 }
1517
1518
1519 /**
1520  * Convert a KSK URI to a string.
1521  *
1522  * @param uri the URI to convert
1523  * @return NULL on error (i.e. keywordCount == 0)
1524  */
1525 static char *
1526 uri_ksk_to_string (const struct GNUNET_FS_Uri *uri)
1527 {
1528   char ** keywords; 
1529   unsigned int keywordCount;
1530   size_t n;
1531   char *ret;
1532   unsigned int i;
1533   unsigned int j;
1534   unsigned int wpos;
1535   size_t slen;
1536   const char *keyword;
1537
1538   if (uri->type != ksk)
1539     return NULL;
1540   keywords = uri->data.ksk.keywords;
1541   keywordCount = uri->data.ksk.keywordCount;
1542   n =
1543     keywordCount + strlen (GNUNET_FS_URI_PREFIX) +
1544     strlen (GNUNET_FS_URI_KSK_INFIX) + 1;
1545   for (i = 0; i < keywordCount; i++)
1546     {
1547       keyword = keywords[i];
1548       slen = strlen (keyword);
1549       n += slen;
1550       for (j = 0; j < slen; j++)
1551         {
1552           if ((j == 0) && (keyword[j] == ' '))
1553             {
1554               n--;
1555               continue;         /* skip leading space */
1556             }
1557           if (needs_percent (keyword[j]))
1558             n += 2;             /* will use %-encoding */
1559         }
1560     }
1561   ret = GNUNET_malloc (n);
1562   strcpy (ret, GNUNET_FS_URI_PREFIX);
1563   strcat (ret, GNUNET_FS_URI_KSK_INFIX);
1564   wpos = strlen (ret);
1565   for (i = 0; i < keywordCount; i++)
1566     {
1567       keyword = keywords[i];
1568       slen = strlen (keyword);
1569       for (j = 0; j < slen; j++)
1570         {
1571           if ((j == 0) && (keyword[j] == ' '))
1572             continue;           /* skip leading space */
1573           if (needs_percent (keyword[j]))
1574             {
1575               sprintf (&ret[wpos], "%%%02X", keyword[j]);
1576               wpos += 3;
1577             }
1578           else
1579             {
1580               ret[wpos++] = keyword[j];
1581             }
1582         }
1583       if (i != keywordCount - 1)
1584         ret[wpos++] = '+';
1585     }
1586   return ret;
1587 }
1588
1589
1590 /**
1591  * Convert SKS URI to a string.
1592  *
1593  * @param uri sks uri to convert
1594  * @return NULL on error
1595  */
1596 static char *
1597 uri_sks_to_string (const struct GNUNET_FS_Uri *uri)
1598 {
1599   const GNUNET_HashCode * namespace;
1600   const char *identifier;
1601   char *ret;
1602   struct GNUNET_CRYPTO_HashAsciiEncoded ns;
1603   
1604   if (uri->type != sks)
1605     return NULL;
1606   namespace = &uri->data.sks.namespace;
1607   identifier = uri->data.sks.identifier;
1608   GNUNET_CRYPTO_hash_to_enc (namespace, &ns);
1609   GNUNET_asprintf (&ret,
1610                    "%s%s%s/%s",
1611                    GNUNET_FS_URI_PREFIX, 
1612                    GNUNET_FS_URI_SKS_INFIX,
1613                    (const char *) &ns, identifier);
1614   return ret;
1615 }
1616
1617
1618 /**
1619  * Convert a CHK URI to a string.
1620  *
1621  * @param uri chk uri to convert
1622  * @return NULL on error
1623  */
1624 static char *
1625 uri_chk_to_string (const struct GNUNET_FS_Uri *uri)
1626 {
1627   const struct FileIdentifier * fi;
1628   char *ret;
1629   struct GNUNET_CRYPTO_HashAsciiEncoded keyhash;
1630   struct GNUNET_CRYPTO_HashAsciiEncoded queryhash;
1631
1632   if (uri->type != chk)
1633     return NULL;
1634   fi = &uri->data.chk;
1635   GNUNET_CRYPTO_hash_to_enc (&fi->chk.key, &keyhash);
1636   GNUNET_CRYPTO_hash_to_enc (&fi->chk.query, &queryhash);
1637
1638   GNUNET_asprintf (&ret,
1639                    "%s%s%s.%s.%llu",
1640                    GNUNET_FS_URI_PREFIX,
1641                    GNUNET_FS_URI_CHK_INFIX,
1642                    (const char *) &keyhash, 
1643                    (const char *) &queryhash,
1644                    GNUNET_ntohll (fi->file_length));
1645   return ret;
1646 }
1647
1648 /**
1649  * Convert binary data to a string.
1650  *
1651  * @param data binary data to convert
1652  * @param size number of bytes in data
1653  * @return converted data
1654  */
1655 static char *
1656 bin2enc (const void *data, size_t size)
1657 {
1658   /**
1659    * 64 characters for encoding, 6 bits per character
1660    */
1661   static char *tbl =
1662     "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=";
1663   
1664   size_t len;
1665   size_t pos;
1666   unsigned int bits;
1667   unsigned int hbits;
1668   char *ret;
1669
1670   GNUNET_assert (strlen (tbl) == 64);
1671   len = size * 8 / 6;
1672   if (((size * 8) % 6) != 0)
1673     len++;
1674   ret = GNUNET_malloc (len + 1);
1675   ret[len] = '\0';
1676   len = 0;
1677   bits = 0;
1678   hbits = 0;
1679   for (pos = 0; pos < size; pos++)
1680     {
1681       bits |= ((((const unsigned char *) data)[pos]) << hbits);
1682       hbits += 8;
1683       while (hbits >= 6)
1684         {
1685           ret[len++] = tbl[bits & 63];
1686           bits >>= 6;
1687           hbits -= 6;
1688         }
1689     }
1690   if (hbits > 0)
1691     ret[len++] = tbl[bits & 63];
1692   return ret;
1693 }
1694
1695
1696 /**
1697  * Convert a LOC URI to a string.
1698  *
1699  * @param uri loc uri to convert
1700  * @return NULL on error
1701  */
1702 static char *
1703 uri_loc_to_string (const struct GNUNET_FS_Uri *uri)
1704 {
1705   char *ret;
1706   struct GNUNET_CRYPTO_HashAsciiEncoded keyhash;
1707   struct GNUNET_CRYPTO_HashAsciiEncoded queryhash;
1708   char *peerId;
1709   char *peerSig;
1710
1711   GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.key, &keyhash);
1712   GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.query, &queryhash);
1713   peerId = bin2enc (&uri->data.loc.peer,
1714                     sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1715   peerSig = bin2enc (&uri->data.loc.contentSignature, 
1716                      sizeof (struct GNUNET_CRYPTO_RsaSignature));
1717   GNUNET_asprintf (&ret,
1718                    "%s%s%s.%s.%llu.%s.%s.%llu",
1719                    GNUNET_FS_URI_PREFIX,
1720                    GNUNET_FS_URI_LOC_INFIX,
1721                    (const char *) &keyhash,
1722                    (const char *) &queryhash,
1723                    (unsigned long long) GNUNET_ntohll (uri->data.loc.fi.file_length),
1724                    peerId,
1725                    peerSig,
1726                    (unsigned long long) uri->data.loc.expirationTime.value);
1727   GNUNET_free (peerSig);
1728   GNUNET_free (peerId);
1729   return ret;
1730 }
1731
1732
1733 /**
1734  * Convert a URI to a UTF-8 String.
1735  *
1736  * @param uri uri to convert to a string
1737  * @return the UTF-8 string
1738  */
1739 char *
1740 GNUNET_FS_uri_to_string (const struct GNUNET_FS_Uri *uri)
1741 {
1742   if (uri == NULL)
1743     {
1744       GNUNET_break (0);
1745       return NULL;
1746     }
1747   switch (uri->type)
1748     {
1749     case ksk:
1750       return uri_ksk_to_string (uri);
1751     case sks:
1752       return uri_sks_to_string (uri);
1753     case chk:
1754       return uri_chk_to_string (uri);
1755     case loc:
1756       return uri_loc_to_string (uri);
1757     default:
1758       GNUNET_break (0);
1759       return NULL;
1760     }
1761 }
1762
1763 /* end of fs_uri.c */