improving comments
[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
103                                               *cfg,
104                                               GNUNET_PSEUDONYM_Iterator
105                                               iterator, void *closure)
106 {
107   struct DiscoveryCallback *list;
108
109   list = GNUNET_malloc (sizeof (struct DiscoveryCallback));
110   list->callback = iterator;
111   list->closure = closure;
112   list->next = head;
113   head = list;
114   GNUNET_PSEUDONYM_list_all (cfg, iterator, closure);
115   return GNUNET_OK;
116 }
117
118 /**
119  * Unregister pseudonym discovery callback.
120  * @param iterator iterator over pseudonym
121  * @param closure point to a closure
122  */
123 int
124 GNUNET_PSEUDONYM_discovery_callback_unregister (GNUNET_PSEUDONYM_Iterator
125                                                 iterator, void *closure)
126 {
127   struct DiscoveryCallback *prev;
128   struct DiscoveryCallback *pos;
129
130   prev = NULL;
131   pos = head;
132   while ((pos != NULL) &&
133          ((pos->callback != iterator) || (pos->closure != closure)))
134     {
135       prev = pos;
136       pos = pos->next;
137     }
138   if (pos == NULL)
139     return GNUNET_SYSERR;
140   if (prev == NULL)
141     head = pos->next;
142   else
143     prev->next = pos->next;
144   GNUNET_free (pos);
145   return GNUNET_OK;
146 }
147
148
149 /**
150  * Get the filename (or directory name) for the given
151  * pseudonym identifier and directory prefix.
152  * @param cfg configuration to use
153  * @param prefix path components to append to the private directory name
154  * @param psid hash code of pseudonym, can be NULL
155  * @return filename of the pseudonym (if psid != NULL) or directory with the data (if psid == NULL)
156  */
157 static char *
158 get_data_filename (const struct GNUNET_CONFIGURATION_Handle
159                    *cfg, const char *prefix, const GNUNET_HashCode * psid)
160 {
161   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
162
163   if (psid != NULL)
164     GNUNET_CRYPTO_hash_to_enc (psid, &enc);
165   return GNUNET_DISK_get_home_filename (cfg,
166                                         GNUNET_CLIENT_SERVICE_NAME,
167                                         prefix,
168                                         (psid ==
169                                          NULL) ? NULL : (const char *) &enc,
170                                         NULL);
171 }
172
173
174 /**
175  * Write the pseudonym infomation into a file
176  * @param cfg configuration to use
177  * @param nsid hash code of a pseudonym
178  * @param meta meta data to be written into a file
179  * @param ranking ranking of a pseudonym
180  * @param ns_name name of a pseudonym
181  */
182 static void
183 write_pseudonym_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
184                       const GNUNET_HashCode * nsid,
185                       const struct GNUNET_CONTAINER_MetaData *meta,
186                       int32_t ranking, const char *ns_name)
187 {
188   char *fn;
189   struct GNUNET_BIO_WriteHandle *fileW;
190
191   fn = get_data_filename (cfg, PS_METADATA_DIR, nsid);
192   GNUNET_assert (fn != NULL);
193   fileW = GNUNET_BIO_write_open(fn);
194   if (NULL != fileW) 
195     {
196       if ( (GNUNET_OK != GNUNET_BIO_write_int32(fileW, ranking)) ||
197            (GNUNET_OK != GNUNET_BIO_write_string(fileW, ns_name)) ||
198            (GNUNET_OK != GNUNET_BIO_write_meta_data(fileW, meta)) )
199         {
200           GNUNET_BIO_write_close(fileW);
201           GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
202           GNUNET_free (fn);
203           return;
204         }
205       if (GNUNET_OK != GNUNET_BIO_write_close(fileW))
206         {
207           GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
208           GNUNET_free (fn);
209           return;
210         }
211     }
212   GNUNET_free (fn);
213   /* create entry for pseudonym name in names */
214   GNUNET_free_non_null (GNUNET_PSEUDONYM_id_to_name (cfg, nsid));
215 }
216
217
218 /**
219  * read the pseudonym infomation from a file
220  * @param cfg configuration to use
221  * @param nsid hash code of a pseudonym
222  * @param meta meta data to be read from a file
223  * @param ranking ranking of a pseudonym
224  * @param ns_name name of a pseudonym
225  */
226 static int
227 read_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
228            const GNUNET_HashCode * nsid,
229            struct GNUNET_CONTAINER_MetaData **meta,
230            int32_t * ranking, char **ns_name)
231 {
232   char *fn;
233   char *emsg;
234   struct GNUNET_BIO_ReadHandle *fileR;
235
236   fn = get_data_filename (cfg, PS_METADATA_DIR, nsid);
237   GNUNET_assert (fn != NULL);
238   fileR = GNUNET_BIO_read_open(fn);
239   if (fileR == NULL)
240     {
241       GNUNET_free (fn);
242       return GNUNET_SYSERR;
243     }
244   if ( (GNUNET_OK != GNUNET_BIO_read_int32__(fileR, "Read int32 error!", ranking)) ||
245        (GNUNET_OK != GNUNET_BIO_read_string(fileR, "Read string error!", ns_name, 200)) ||
246        (GNUNET_OK != GNUNET_BIO_read_meta_data(fileR, "Read meta data error!", meta)) )
247     {
248       GNUNET_BIO_read_close(fileR, &emsg);
249       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
250       GNUNET_free (fn);
251       return GNUNET_SYSERR;
252     }
253   emsg = NULL;
254   if (GNUNET_OK != GNUNET_BIO_read_close(fileR, &emsg))
255     {
256       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
257                   _("Failed to parse metadata about pseudonym from file `%s': %s\n"),
258                   fn,
259                   emsg);
260       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
261       GNUNET_free_non_null (emsg);
262       GNUNET_free (fn);
263       return GNUNET_SYSERR;
264     }
265   GNUNET_free (fn);
266   return GNUNET_OK;
267 }
268
269
270
271 /**
272  * Return the unique, human readable name for the given namespace.
273  *
274  * @param cfg configuration 
275  * @param nsid cryptographic ID of the namespace
276  * @return NULL on failure (should never happen)
277  */
278 char *
279 GNUNET_PSEUDONYM_id_to_name (const struct GNUNET_CONFIGURATION_Handle *cfg,
280                              const GNUNET_HashCode * nsid)
281 {
282   struct GNUNET_CONTAINER_MetaData *meta;
283   char *name;
284   GNUNET_HashCode nh;
285   char *fn;
286   uint64_t len;
287   struct GNUNET_DISK_FileHandle *fh;
288   unsigned int i;
289   unsigned int idx;
290   char *ret;
291   struct stat sbuf;
292   int32_t temp = 0;
293   int32_t *rank = &temp;
294
295   meta = NULL;
296   name = NULL;
297   if (GNUNET_OK == read_info (cfg, nsid, &meta, rank, &name))
298     {
299       if ((meta != NULL) && (name == NULL))
300         name = GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
301                                                               EXTRACTOR_TITLE,
302                                                               EXTRACTOR_FILENAME,
303                                                               EXTRACTOR_DESCRIPTION,
304                                                               EXTRACTOR_SUBJECT,
305                                                               EXTRACTOR_PUBLISHER,
306                                                               EXTRACTOR_AUTHOR,
307                                                               EXTRACTOR_COMMENT,
308                                                               EXTRACTOR_SUMMARY,
309                                                               EXTRACTOR_OWNER,
310                                                               -1);
311       if (meta != NULL)
312         {
313           GNUNET_CONTAINER_meta_data_destroy (meta);
314           meta = NULL;
315         }
316     }
317   if (name == NULL)
318     name = GNUNET_strdup (_("no-name"));
319   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
320   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
321   GNUNET_assert (fn != NULL);
322
323   len = 0;
324   if (0 == STAT (fn, &sbuf))
325     GNUNET_DISK_file_size (fn, &len, GNUNET_YES);
326   fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_CREATE
327                               | GNUNET_DISK_OPEN_READWRITE,
328                               GNUNET_DISK_PERM_USER_READ |
329                               GNUNET_DISK_PERM_USER_WRITE);
330   i = 0;
331   idx = -1;
332   while ((len >= sizeof (GNUNET_HashCode)) &&
333          (sizeof (GNUNET_HashCode)
334           == GNUNET_DISK_file_read (fh, &nh, sizeof (GNUNET_HashCode))))
335     {
336       if (0 == memcmp (&nh, nsid, sizeof (GNUNET_HashCode)))
337         {
338           idx = i;
339           break;
340         }
341       i++;
342       len -= sizeof (GNUNET_HashCode);
343     }
344   if (idx == -1)
345     {
346       idx = i;
347       if (sizeof (GNUNET_HashCode) !=
348           GNUNET_DISK_file_write (fh, nsid, sizeof (GNUNET_HashCode)))
349         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
350     }
351   GNUNET_DISK_file_close (fh);
352   ret = GNUNET_malloc (strlen (name) + 32);
353   GNUNET_snprintf (ret, strlen (name) + 32, "%s-%u", name, idx);
354   GNUNET_free (name);
355   GNUNET_free (fn);
356   return ret;
357 }
358
359 /**
360  * Get the namespace ID belonging to the given namespace name.
361  *
362  * @param cfg configuration to use
363  * @param ns_uname human-readable name for the namespace
364  * @param nsid set to namespace ID based on 'ns_uname'
365  * @return GNUNET_OK on success
366  */
367 int
368 GNUNET_PSEUDONYM_name_to_id (const struct GNUNET_CONFIGURATION_Handle *cfg,
369                              const char *ns_uname, GNUNET_HashCode * nsid)
370 {
371   size_t slen;
372   uint64_t len;
373   unsigned int idx;
374   char *name;
375   GNUNET_HashCode nh;
376   char *fn;
377   struct GNUNET_DISK_FileHandle *fh;
378
379   idx = -1;
380   slen = strlen (ns_uname);
381   while ((slen > 0) && (1 != sscanf (&ns_uname[slen - 1], "-%u", &idx)))
382     slen--;
383   if (slen == 0)
384     return GNUNET_SYSERR;
385   name = GNUNET_strdup (ns_uname);
386   name[slen - 1] = '\0';
387   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
388   GNUNET_free (name);
389   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
390   GNUNET_assert (fn != NULL);
391
392   if ((GNUNET_OK != GNUNET_DISK_file_test (fn) ||
393        (GNUNET_OK != GNUNET_DISK_file_size (fn, &len, GNUNET_YES))) ||
394       ((idx + 1) * sizeof (GNUNET_HashCode) > len))
395     {
396       GNUNET_free (fn);
397       return GNUNET_SYSERR;
398     }
399   fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_CREATE
400                               | GNUNET_DISK_OPEN_READWRITE,
401                               GNUNET_DISK_PERM_USER_READ |
402                               GNUNET_DISK_PERM_USER_WRITE);
403   GNUNET_free (fn);
404   GNUNET_DISK_file_seek (fh, idx * sizeof (GNUNET_HashCode),
405                          GNUNET_DISK_SEEK_SET);
406   if (sizeof (GNUNET_HashCode) !=
407       GNUNET_DISK_file_read (fh, nsid, sizeof (GNUNET_HashCode)))
408     {
409       GNUNET_DISK_file_close (fh);
410       return GNUNET_SYSERR;
411     }
412   GNUNET_DISK_file_close (fh);
413   return GNUNET_OK;
414 }
415
416
417
418 /**
419  * struct used to list the pseudonym
420  */
421 struct ListPseudonymClosure
422 {
423
424   /**
425    * iterator over pseudonym
426    */
427   GNUNET_PSEUDONYM_Iterator iterator;
428
429   /**
430    * Closure for iterator.
431    */
432   void *closure;
433
434   /**
435    * Configuration to use.
436    */
437   const struct GNUNET_CONFIGURATION_Handle *cfg;
438 };
439
440
441
442 /**
443  * the help function to list all available pseudonyms
444  * @param cls point to a struct ListPseudonymClosure
445  * @param fullname name of pseudonym
446  */
447 static int
448 list_pseudonym_helper (void *cls, const char *fullname)
449 {
450   struct ListPseudonymClosure *c = cls;
451   int ret;
452   GNUNET_HashCode id;
453   int rating;
454   struct GNUNET_CONTAINER_MetaData *meta;
455   const char *fn;
456   char *str;
457
458   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
459     return GNUNET_OK;
460   fn =
461     &fullname[strlen (fullname) + 1 -
462               sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
463   if (fn[-1] != DIR_SEPARATOR)
464     return GNUNET_OK;
465   ret = GNUNET_OK;
466   if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (fn, &id))
467     return GNUNET_OK;           /* invalid name */
468   str = NULL;
469   if (GNUNET_OK != read_info (c->cfg, &id, &meta, &rating, &str))
470     return GNUNET_OK;           /* ignore entry */
471   GNUNET_free_non_null (str);
472   if (c->iterator != NULL)
473     ret = c->iterator (c->closure, &id, meta, rating);
474   GNUNET_CONTAINER_meta_data_destroy (meta);
475   return ret;
476 }
477
478
479 /**
480  * List all available pseudonyms.
481  *
482  * @param cfg overall configuration 
483  * @param iterator function to call for each pseudonym
484  * @param closure closure for iterator
485  * @return number of pseudonyms found
486  */
487 int
488 GNUNET_PSEUDONYM_list_all (const struct GNUNET_CONFIGURATION_Handle *cfg,
489                            GNUNET_PSEUDONYM_Iterator iterator, void *closure)
490 {
491   struct ListPseudonymClosure cls;
492   char *fn;
493   int ret;
494
495   cls.iterator = iterator;
496   cls.closure = closure;
497   cls.cfg = cfg;
498   fn = get_data_filename (cfg, PS_METADATA_DIR, NULL);
499   GNUNET_assert (fn != NULL);
500   GNUNET_DISK_directory_create (fn);
501   ret = GNUNET_DISK_directory_scan (fn, &list_pseudonym_helper, &cls);
502   GNUNET_free (fn);
503   return ret;
504 }
505
506 /**
507  * Change the ranking of a pseudonym.
508  *
509  * @param cfg overall configuration
510  * @param nsid id of the pseudonym
511  * @param delta by how much should the rating be
512  *  changed?
513  * @return new rating of the pseudonym
514  */
515 int
516 GNUNET_PSEUDONYM_rank (const struct GNUNET_CONFIGURATION_Handle *cfg,
517                        const GNUNET_HashCode * nsid, int delta)
518 {
519   struct GNUNET_CONTAINER_MetaData *meta;
520   int ret;
521   int32_t ranking;
522   char *name;
523
524   name = NULL;
525   ret = read_info (cfg, nsid, &meta, &ranking, &name);
526   if (ret == GNUNET_SYSERR)
527     {
528       ranking = 0;
529       meta = GNUNET_CONTAINER_meta_data_create ();
530     }
531   ranking += delta;
532   write_pseudonym_info (cfg, nsid, meta, ranking, name);
533   GNUNET_CONTAINER_meta_data_destroy (meta);
534   GNUNET_free_non_null (name);
535   return ranking;
536 }
537
538 /**
539  * Insert metadata into existing MD record (passed as cls).
540  *
541  * @param cls metadata to add to
542  * @param type type of entry to insert
543  * @param data value of entry to insert
544  */
545 static int
546 merge_meta_helper (void *cls, EXTRACTOR_KeywordType type, const char *data)
547 {
548   struct GNUNET_CONTAINER_MetaData *meta = cls;
549   GNUNET_CONTAINER_meta_data_insert (meta, type, data);
550   return GNUNET_OK;
551 }
552
553
554
555 /**
556  * Add a pseudonym to the set of known pseudonyms.
557  * For all pseudonym advertisements that we discover
558  * FS should automatically call this function.
559  *
560  * @param cfg overall configuration
561  * @param id the pseudonym identifier
562  * @param meta metadata for the pseudonym
563  */
564 void
565 GNUNET_PSEUDONYM_add (const struct GNUNET_CONFIGURATION_Handle *cfg,
566                       const GNUNET_HashCode * id,
567                       const struct GNUNET_CONTAINER_MetaData *meta)
568 {
569   char *name;
570   int32_t ranking;
571   struct GNUNET_CONTAINER_MetaData *old;
572   char *fn;
573   struct stat sbuf;
574
575   ranking = 0;
576   fn = get_data_filename (cfg, PS_METADATA_DIR, id);
577   GNUNET_assert (fn != NULL);
578
579   if ((0 == STAT (fn, &sbuf)) &&
580       (GNUNET_OK == read_info (cfg, id, &old, &ranking, &name)))
581     {
582       GNUNET_CONTAINER_meta_data_get_contents (meta, &merge_meta_helper, old);
583       write_pseudonym_info (cfg, id, old, ranking, name);
584       GNUNET_CONTAINER_meta_data_destroy (old);
585       GNUNET_free_non_null (name);
586     }
587   else
588     {
589       write_pseudonym_info (cfg, id, meta, ranking, NULL);
590     }
591   GNUNET_free (fn);
592   internal_notify (id, meta, ranking);
593 }
594
595
596
597
598
599 /* end of pseudonym.c */