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