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