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