fixing 1753
[oweals/gnunet.git] / src / util / pseudonym.c
1 /*
2      This file is part of GNUnet
3      (C) 2003, 2004, 2005, 2006, 2007, 2008 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 util/pseudonym.c
23  * @brief helper functions
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_common.h"
29 #include "gnunet_container_lib.h"
30 #include "gnunet_disk_lib.h"
31 #include "gnunet_pseudonym_lib.h"
32 #include "gnunet_bio_lib.h"
33
34 /**
35  * Name of the directory which stores meta data for pseudonym
36  */
37 #define PS_METADATA_DIR DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonyms" DIR_SEPARATOR_STR "metadata" DIR_SEPARATOR_STR
38
39 /**
40  * Name of the directory which stores names for pseudonyms
41  */
42 #define PS_NAMES_DIR    DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonyms" DIR_SEPARATOR_STR "names"    DIR_SEPARATOR_STR
43
44
45 /**
46  * Registered callbacks for discovery of pseudonyms.
47  */
48 struct DiscoveryCallback
49 {
50   /**
51    * This is a linked list.
52    */
53   struct DiscoveryCallback *next;
54
55   /**
56    * Function to call each time a pseudonym is discovered.
57    */
58   GNUNET_PSEUDONYM_Iterator callback;
59
60   /**
61    * Closure for callback.
62    */
63   void *closure;
64 };
65
66
67 /**
68  * Head of the linked list of functions to call when
69  * new pseudonyms are added.
70  */
71 static struct DiscoveryCallback *head;
72
73 /**
74  * Internal notification about new tracked URI.
75  * @param id a point to the hash code of pseudonym
76  * @param md meta data to be written
77  * @param rating rating of pseudonym
78  */
79 static void
80 internal_notify (const GNUNET_HashCode * id,
81                  const struct GNUNET_CONTAINER_MetaData *md, int rating)
82 {
83   struct DiscoveryCallback *pos;
84
85   pos = head;
86   while (pos != NULL)
87   {
88     pos->callback (pos->closure, id, md, rating);
89     pos = pos->next;
90   }
91 }
92
93 /**
94  * Register callback to be invoked whenever we discover
95  * a new pseudonym.
96  * @param cfg configuration to use
97  * @param iterator iterator over pseudonym
98  * @param closure point to a closure
99  */
100 int
101 GNUNET_PSEUDONYM_discovery_callback_register (const struct
102                                               GNUNET_CONFIGURATION_Handle *cfg,
103                                               GNUNET_PSEUDONYM_Iterator
104                                               iterator, void *closure)
105 {
106   struct DiscoveryCallback *list;
107
108   list = GNUNET_malloc (sizeof (struct DiscoveryCallback));
109   list->callback = iterator;
110   list->closure = closure;
111   list->next = head;
112   head = list;
113   GNUNET_PSEUDONYM_list_all (cfg, iterator, closure);
114   return GNUNET_OK;
115 }
116
117 /**
118  * Unregister pseudonym discovery callback.
119  * @param iterator iterator over pseudonym
120  * @param closure point to a closure
121  */
122 int
123 GNUNET_PSEUDONYM_discovery_callback_unregister (GNUNET_PSEUDONYM_Iterator
124                                                 iterator, void *closure)
125 {
126   struct DiscoveryCallback *prev;
127   struct DiscoveryCallback *pos;
128
129   prev = NULL;
130   pos = head;
131   while ((pos != NULL) &&
132          ((pos->callback != iterator) || (pos->closure != closure)))
133   {
134     prev = pos;
135     pos = pos->next;
136   }
137   if (pos == NULL)
138     return GNUNET_SYSERR;
139   if (prev == NULL)
140     head = pos->next;
141   else
142     prev->next = pos->next;
143   GNUNET_free (pos);
144   return GNUNET_OK;
145 }
146
147
148 /**
149  * Get the filename (or directory name) for the given
150  * pseudonym identifier and directory prefix.
151  * @param cfg configuration to use
152  * @param prefix path components to append to the private directory name
153  * @param psid hash code of pseudonym, can be NULL
154  * @return filename of the pseudonym (if psid != NULL) or directory with the data (if psid == NULL)
155  */
156 static char *
157 get_data_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
158                    const char *prefix, const GNUNET_HashCode * psid)
159 {
160   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
161
162   if (psid != NULL)
163     GNUNET_CRYPTO_hash_to_enc (psid, &enc);
164   return GNUNET_DISK_get_home_filename (cfg, GNUNET_CLIENT_SERVICE_NAME, prefix,
165                                         (psid ==
166                                          NULL) ? NULL : (const char *) &enc,
167                                         NULL);
168 }
169
170
171 /**
172  * Write the pseudonym infomation into a file
173  * @param cfg configuration to use
174  * @param nsid hash code of a pseudonym
175  * @param meta meta data to be written into a file
176  * @param ranking ranking of a pseudonym
177  * @param ns_name name of a pseudonym
178  */
179 static void
180 write_pseudonym_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
181                       const GNUNET_HashCode * nsid,
182                       const struct GNUNET_CONTAINER_MetaData *meta,
183                       int32_t ranking, const char *ns_name)
184 {
185   char *fn;
186   struct GNUNET_BIO_WriteHandle *fileW;
187
188   fn = get_data_filename (cfg, PS_METADATA_DIR, nsid);
189   GNUNET_assert (fn != NULL);
190   fileW = GNUNET_BIO_write_open (fn);
191   if (NULL != fileW)
192   {
193     if ((GNUNET_OK != GNUNET_BIO_write_int32 (fileW, ranking)) ||
194         (GNUNET_OK != GNUNET_BIO_write_string (fileW, ns_name)) ||
195         (GNUNET_OK != GNUNET_BIO_write_meta_data (fileW, meta)))
196     {
197       (void) GNUNET_BIO_write_close (fileW);
198       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
199       GNUNET_free (fn);
200       return;
201     }
202     if (GNUNET_OK != GNUNET_BIO_write_close (fileW))
203     {
204       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
205       GNUNET_free (fn);
206       return;
207     }
208   }
209   GNUNET_free (fn);
210   /* create entry for pseudonym name in names */
211   /* FIXME: 90% of what this call does is not needed
212    * here => refactor code to only create the entry! */
213   GNUNET_free_non_null (GNUNET_PSEUDONYM_id_to_name (cfg, nsid));
214 }
215
216
217 /**
218  * read the pseudonym infomation from a file
219  * @param cfg configuration to use
220  * @param nsid hash code of a pseudonym
221  * @param meta meta data to be read from a file
222  * @param ranking ranking of a pseudonym
223  * @param ns_name name of a pseudonym
224  */
225 static int
226 read_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
227            const GNUNET_HashCode * nsid,
228            struct GNUNET_CONTAINER_MetaData **meta, int32_t * ranking,
229            char **ns_name)
230 {
231   char *fn;
232   char *emsg;
233   struct GNUNET_BIO_ReadHandle *fileR;
234
235   fn = get_data_filename (cfg, PS_METADATA_DIR, nsid);
236   GNUNET_assert (fn != NULL);
237   fileR = GNUNET_BIO_read_open (fn);
238   if (fileR == NULL)
239   {
240     GNUNET_free (fn);
241     return GNUNET_SYSERR;
242   }
243   emsg = NULL;
244   *ns_name = NULL;
245   if ((GNUNET_OK != GNUNET_BIO_read_int32 (fileR, ranking)) ||
246       (GNUNET_OK !=
247        GNUNET_BIO_read_string (fileR, "Read string error!", ns_name, 200)) ||
248       (GNUNET_OK !=
249        GNUNET_BIO_read_meta_data (fileR, "Read meta data error!", meta)))
250   {
251     (void) GNUNET_BIO_read_close (fileR, &emsg);
252     GNUNET_free_non_null (emsg);
253     GNUNET_free_non_null (*ns_name);
254     *ns_name = NULL;
255     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
256     GNUNET_free (fn);
257     return GNUNET_SYSERR;
258   }
259   if (GNUNET_OK != GNUNET_BIO_read_close (fileR, &emsg))
260   {
261     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
262                 _
263                 ("Failed to parse metadata about pseudonym from file `%s': %s\n"),
264                 fn, emsg);
265     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
266     GNUNET_CONTAINER_meta_data_destroy (*meta);
267     *meta = NULL;
268     GNUNET_free_non_null (*ns_name);
269     *ns_name = NULL;
270     GNUNET_free_non_null (emsg);
271     GNUNET_free (fn);
272     return GNUNET_SYSERR;
273   }
274   GNUNET_free (fn);
275   return GNUNET_OK;
276 }
277
278
279
280 /**
281  * Return the unique, human readable name for the given namespace.
282  *
283  * @param cfg configuration
284  * @param nsid cryptographic ID of the namespace
285  * @return NULL on failure (should never happen)
286  */
287 char *
288 GNUNET_PSEUDONYM_id_to_name (const struct GNUNET_CONFIGURATION_Handle *cfg,
289                              const GNUNET_HashCode * nsid)
290 {
291   struct GNUNET_CONTAINER_MetaData *meta;
292   char *name;
293   GNUNET_HashCode nh;
294   char *fn;
295   uint64_t len;
296   struct GNUNET_DISK_FileHandle *fh;
297   unsigned int i;
298   unsigned int idx;
299   char *ret;
300   struct stat sbuf;
301   int32_t temp = 0;
302   int32_t *rank = &temp;
303
304   meta = NULL;
305   name = NULL;
306   if (GNUNET_OK == read_info (cfg, nsid, &meta, rank, &name))
307   {
308     if ((meta != NULL) && (name == NULL))
309       name =
310           GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
311                                                          EXTRACTOR_METATYPE_TITLE,
312                                                          EXTRACTOR_METATYPE_FILENAME,
313                                                          EXTRACTOR_METATYPE_DESCRIPTION,
314                                                          EXTRACTOR_METATYPE_SUBJECT,
315                                                          EXTRACTOR_METATYPE_PUBLISHER,
316                                                          EXTRACTOR_METATYPE_AUTHOR_NAME,
317                                                          EXTRACTOR_METATYPE_COMMENT,
318                                                          EXTRACTOR_METATYPE_SUMMARY,
319                                                          -1);
320     if (meta != NULL)
321     {
322       GNUNET_CONTAINER_meta_data_destroy (meta);
323       meta = NULL;
324     }
325   }
326   if (name == NULL)
327     name = GNUNET_strdup (_("no-name"));
328   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
329   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
330   GNUNET_assert (fn != NULL);
331
332   len = 0;
333   if (0 == STAT (fn, &sbuf))
334     GNUNET_DISK_file_size (fn, &len, GNUNET_YES);
335   fh = GNUNET_DISK_file_open (fn,
336                               GNUNET_DISK_OPEN_CREATE |
337                               GNUNET_DISK_OPEN_READWRITE,
338                               GNUNET_DISK_PERM_USER_READ |
339                               GNUNET_DISK_PERM_USER_WRITE);
340   i = 0;
341   idx = -1;
342   while ((len >= sizeof (GNUNET_HashCode)) &&
343          (sizeof (GNUNET_HashCode) ==
344           GNUNET_DISK_file_read (fh, &nh, sizeof (GNUNET_HashCode))))
345   {
346     if (0 == memcmp (&nh, nsid, sizeof (GNUNET_HashCode)))
347     {
348       idx = i;
349       break;
350     }
351     i++;
352     len -= sizeof (GNUNET_HashCode);
353   }
354   if (idx == -1)
355   {
356     idx = i;
357     if (sizeof (GNUNET_HashCode) !=
358         GNUNET_DISK_file_write (fh, nsid, sizeof (GNUNET_HashCode)))
359       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
360   }
361   GNUNET_DISK_file_close (fh);
362   ret = GNUNET_malloc (strlen (name) + 32);
363   GNUNET_snprintf (ret, strlen (name) + 32, "%s-%u", name, idx);
364   GNUNET_free (name);
365   GNUNET_free (fn);
366   return ret;
367 }
368
369 /**
370  * Get the namespace ID belonging to the given namespace name.
371  *
372  * @param cfg configuration to use
373  * @param ns_uname human-readable name for the namespace
374  * @param nsid set to namespace ID based on 'ns_uname'
375  * @return GNUNET_OK on success
376  */
377 int
378 GNUNET_PSEUDONYM_name_to_id (const struct GNUNET_CONFIGURATION_Handle *cfg,
379                              const char *ns_uname, GNUNET_HashCode * nsid)
380 {
381   size_t slen;
382   uint64_t len;
383   unsigned int idx;
384   char *name;
385   GNUNET_HashCode nh;
386   char *fn;
387   struct GNUNET_DISK_FileHandle *fh;
388
389   idx = -1;
390   slen = strlen (ns_uname);
391   while ((slen > 0) && (1 != sscanf (&ns_uname[slen - 1], "-%u", &idx)))
392     slen--;
393   if (slen == 0)
394     return GNUNET_SYSERR;
395   name = GNUNET_strdup (ns_uname);
396   name[slen - 1] = '\0';
397   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
398   GNUNET_free (name);
399   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
400   GNUNET_assert (fn != NULL);
401
402   if ((GNUNET_OK != GNUNET_DISK_file_test (fn) ||
403        (GNUNET_OK != GNUNET_DISK_file_size (fn, &len, GNUNET_YES))) ||
404       ((idx + 1) * sizeof (GNUNET_HashCode) > len))
405   {
406     GNUNET_free (fn);
407     return GNUNET_SYSERR;
408   }
409   fh = GNUNET_DISK_file_open (fn,
410                               GNUNET_DISK_OPEN_CREATE |
411                               GNUNET_DISK_OPEN_READWRITE,
412                               GNUNET_DISK_PERM_USER_READ |
413                               GNUNET_DISK_PERM_USER_WRITE);
414   GNUNET_free (fn);
415   GNUNET_DISK_file_seek (fh, idx * sizeof (GNUNET_HashCode),
416                          GNUNET_DISK_SEEK_SET);
417   if (sizeof (GNUNET_HashCode) !=
418       GNUNET_DISK_file_read (fh, nsid, sizeof (GNUNET_HashCode)))
419   {
420     GNUNET_DISK_file_close (fh);
421     return GNUNET_SYSERR;
422   }
423   GNUNET_DISK_file_close (fh);
424   return GNUNET_OK;
425 }
426
427
428
429 /**
430  * struct used to list the pseudonym
431  */
432 struct ListPseudonymClosure
433 {
434
435   /**
436    * iterator over pseudonym
437    */
438   GNUNET_PSEUDONYM_Iterator iterator;
439
440   /**
441    * Closure for iterator.
442    */
443   void *closure;
444
445   /**
446    * Configuration to use.
447    */
448   const struct GNUNET_CONFIGURATION_Handle *cfg;
449 };
450
451
452
453 /**
454  * the help function to list all available pseudonyms
455  * @param cls point to a struct ListPseudonymClosure
456  * @param fullname name of pseudonym
457  */
458 static int
459 list_pseudonym_helper (void *cls, const char *fullname)
460 {
461   struct ListPseudonymClosure *c = cls;
462   int ret;
463   GNUNET_HashCode id;
464   int rating;
465   struct GNUNET_CONTAINER_MetaData *meta;
466   const char *fn;
467   char *str;
468
469   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
470     return GNUNET_OK;
471   fn = &fullname[strlen (fullname) + 1 -
472                  sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
473   if (fn[-1] != DIR_SEPARATOR)
474     return GNUNET_OK;
475   ret = GNUNET_OK;
476   if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (fn, &id))
477     return GNUNET_OK;           /* invalid name */
478   str = NULL;
479   if (GNUNET_OK != read_info (c->cfg, &id, &meta, &rating, &str))
480     return GNUNET_OK;           /* ignore entry */
481   GNUNET_free_non_null (str);
482   if (c->iterator != NULL)
483     ret = c->iterator (c->closure, &id, meta, rating);
484   GNUNET_CONTAINER_meta_data_destroy (meta);
485   return ret;
486 }
487
488
489 /**
490  * List all available pseudonyms.
491  *
492  * @param cfg overall configuration
493  * @param iterator function to call for each pseudonym
494  * @param closure closure for iterator
495  * @return number of pseudonyms found
496  */
497 int
498 GNUNET_PSEUDONYM_list_all (const struct GNUNET_CONFIGURATION_Handle *cfg,
499                            GNUNET_PSEUDONYM_Iterator iterator, void *closure)
500 {
501   struct ListPseudonymClosure cls;
502   char *fn;
503   int ret;
504
505   cls.iterator = iterator;
506   cls.closure = closure;
507   cls.cfg = cfg;
508   fn = get_data_filename (cfg, PS_METADATA_DIR, NULL);
509   GNUNET_assert (fn != NULL);
510   GNUNET_DISK_directory_create (fn);
511   ret = GNUNET_DISK_directory_scan (fn, &list_pseudonym_helper, &cls);
512   GNUNET_free (fn);
513   return ret;
514 }
515
516
517 /**
518  * Change the ranking of a pseudonym.
519  *
520  * @param cfg overall configuration
521  * @param nsid id of the pseudonym
522  * @param delta by how much should the rating be
523  *  changed?
524  * @return new rating of the pseudonym
525  */
526 int
527 GNUNET_PSEUDONYM_rank (const struct GNUNET_CONFIGURATION_Handle *cfg,
528                        const GNUNET_HashCode * nsid, int delta)
529 {
530   struct GNUNET_CONTAINER_MetaData *meta;
531   int ret;
532   int32_t ranking;
533   char *name;
534
535   name = NULL;
536   ret = read_info (cfg, nsid, &meta, &ranking, &name);
537   if (ret == GNUNET_SYSERR)
538   {
539     ranking = 0;
540     meta = GNUNET_CONTAINER_meta_data_create ();
541   }
542   ranking += delta;
543   write_pseudonym_info (cfg, nsid, meta, ranking, name);
544   GNUNET_CONTAINER_meta_data_destroy (meta);
545   GNUNET_free_non_null (name);
546   return ranking;
547 }
548
549
550 /**
551  * Add a pseudonym to the set of known pseudonyms.
552  * For all pseudonym advertisements that we discover
553  * FS should automatically call this function.
554  *
555  * @param cfg overall configuration
556  * @param id the pseudonym identifier
557  * @param meta metadata for the pseudonym
558  */
559 void
560 GNUNET_PSEUDONYM_add (const struct GNUNET_CONFIGURATION_Handle *cfg,
561                       const GNUNET_HashCode * id,
562                       const struct GNUNET_CONTAINER_MetaData *meta)
563 {
564   char *name;
565   int32_t ranking;
566   struct GNUNET_CONTAINER_MetaData *old;
567   char *fn;
568   struct stat sbuf;
569
570   ranking = 0;
571   fn = get_data_filename (cfg, PS_METADATA_DIR, id);
572   GNUNET_assert (fn != NULL);
573
574   if ((0 == STAT (fn, &sbuf)) &&
575       (GNUNET_OK == read_info (cfg, id, &old, &ranking, &name)))
576   {
577     GNUNET_CONTAINER_meta_data_merge (old, meta);
578     write_pseudonym_info (cfg, id, old, ranking, name);
579     GNUNET_CONTAINER_meta_data_destroy (old);
580     GNUNET_free_non_null (name);
581   }
582   else
583   {
584     write_pseudonym_info (cfg, id, meta, ranking, NULL);
585   }
586   GNUNET_free (fn);
587   internal_notify (id, meta, ranking);
588 }
589
590
591 /* end of pseudonym.c */