fix hypothetical leak
[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           (void) 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   /* FIXME: 90% of what this call does is not needed
215      here => refactor code to only create the entry! */
216   GNUNET_free_non_null (GNUNET_PSEUDONYM_id_to_name (cfg, nsid));
217 }
218
219
220 /**
221  * read the pseudonym infomation from a file
222  * @param cfg configuration to use
223  * @param nsid hash code of a pseudonym
224  * @param meta meta data to be read from a file
225  * @param ranking ranking of a pseudonym
226  * @param ns_name name of a pseudonym
227  */
228 static int
229 read_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
230            const GNUNET_HashCode * nsid,
231            struct GNUNET_CONTAINER_MetaData **meta,
232            int32_t * ranking, char **ns_name)
233 {
234   char *fn;
235   char *emsg;
236   struct GNUNET_BIO_ReadHandle *fileR;
237
238   fn = get_data_filename (cfg, PS_METADATA_DIR, nsid);
239   GNUNET_assert (fn != NULL);
240   fileR = GNUNET_BIO_read_open(fn);
241   if (fileR == NULL)
242     {
243       GNUNET_free (fn);
244       return GNUNET_SYSERR;
245     }
246   emsg = NULL;
247   if ( (GNUNET_OK != GNUNET_BIO_read_int32 (fileR, ranking)) ||
248        (GNUNET_OK != GNUNET_BIO_read_string(fileR, "Read string error!", ns_name, 200)) ||
249        (GNUNET_OK != GNUNET_BIO_read_meta_data(fileR, "Read meta data error!", meta)) )
250     {
251       GNUNET_BIO_read_close(fileR, &emsg);
252       GNUNET_free_non_null (emsg);
253       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
254       GNUNET_free (fn);
255       return GNUNET_SYSERR;
256     }
257   if (GNUNET_OK != GNUNET_BIO_read_close(fileR, &emsg))
258     {
259       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
260                   _("Failed to parse metadata about pseudonym from file `%s': %s\n"),
261                   fn,
262                   emsg);
263       GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
264       GNUNET_CONTAINER_meta_data_destroy (*meta);
265       *meta = NULL;
266       GNUNET_free_non_null (emsg);
267       GNUNET_free (fn);
268       return GNUNET_SYSERR;
269     }
270   GNUNET_free (fn);
271   return GNUNET_OK;
272 }
273
274
275
276 /**
277  * Return the unique, human readable name for the given namespace.
278  *
279  * @param cfg configuration 
280  * @param nsid cryptographic ID of the namespace
281  * @return NULL on failure (should never happen)
282  */
283 char *
284 GNUNET_PSEUDONYM_id_to_name (const struct GNUNET_CONFIGURATION_Handle *cfg,
285                              const GNUNET_HashCode * nsid)
286 {
287   struct GNUNET_CONTAINER_MetaData *meta;
288   char *name;
289   GNUNET_HashCode nh;
290   char *fn;
291   uint64_t len;
292   struct GNUNET_DISK_FileHandle *fh;
293   unsigned int i;
294   unsigned int idx;
295   char *ret;
296   struct stat sbuf;
297   int32_t temp = 0;
298   int32_t *rank = &temp;
299
300   meta = NULL;
301   name = NULL;
302   if (GNUNET_OK == read_info (cfg, nsid, &meta, rank, &name))
303     {
304       if ((meta != NULL) && (name == NULL))
305         name = GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
306                                                               EXTRACTOR_METATYPE_TITLE,
307                                                               EXTRACTOR_METATYPE_FILENAME,
308                                                               EXTRACTOR_METATYPE_DESCRIPTION,
309                                                               EXTRACTOR_METATYPE_SUBJECT,
310                                                               EXTRACTOR_METATYPE_PUBLISHER,
311                                                               EXTRACTOR_METATYPE_AUTHOR_NAME,
312                                                               EXTRACTOR_METATYPE_COMMENT,
313                                                               EXTRACTOR_METATYPE_SUMMARY,
314                                                               -1);
315       if (meta != NULL)
316         {
317           GNUNET_CONTAINER_meta_data_destroy (meta);
318           meta = NULL;
319         }
320     }
321   if (name == NULL)
322     name = GNUNET_strdup (_("no-name"));
323   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
324   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
325   GNUNET_assert (fn != NULL);
326
327   len = 0;
328   if (0 == STAT (fn, &sbuf))
329     GNUNET_DISK_file_size (fn, &len, GNUNET_YES);
330   fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_CREATE
331                               | GNUNET_DISK_OPEN_READWRITE,
332                               GNUNET_DISK_PERM_USER_READ |
333                               GNUNET_DISK_PERM_USER_WRITE);
334   i = 0;
335   idx = -1;
336   while ((len >= sizeof (GNUNET_HashCode)) &&
337          (sizeof (GNUNET_HashCode)
338           == GNUNET_DISK_file_read (fh, &nh, sizeof (GNUNET_HashCode))))
339     {
340       if (0 == memcmp (&nh, nsid, sizeof (GNUNET_HashCode)))
341         {
342           idx = i;
343           break;
344         }
345       i++;
346       len -= sizeof (GNUNET_HashCode);
347     }
348   if (idx == -1)
349     {
350       idx = i;
351       if (sizeof (GNUNET_HashCode) !=
352           GNUNET_DISK_file_write (fh, nsid, sizeof (GNUNET_HashCode)))
353         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn);
354     }
355   GNUNET_DISK_file_close (fh);
356   ret = GNUNET_malloc (strlen (name) + 32);
357   GNUNET_snprintf (ret, strlen (name) + 32, "%s-%u", name, idx);
358   GNUNET_free (name);
359   GNUNET_free (fn);
360   return ret;
361 }
362
363 /**
364  * Get the namespace ID belonging to the given namespace name.
365  *
366  * @param cfg configuration to use
367  * @param ns_uname human-readable name for the namespace
368  * @param nsid set to namespace ID based on 'ns_uname'
369  * @return GNUNET_OK on success
370  */
371 int
372 GNUNET_PSEUDONYM_name_to_id (const struct GNUNET_CONFIGURATION_Handle *cfg,
373                              const char *ns_uname, GNUNET_HashCode * nsid)
374 {
375   size_t slen;
376   uint64_t len;
377   unsigned int idx;
378   char *name;
379   GNUNET_HashCode nh;
380   char *fn;
381   struct GNUNET_DISK_FileHandle *fh;
382
383   idx = -1;
384   slen = strlen (ns_uname);
385   while ((slen > 0) && (1 != sscanf (&ns_uname[slen - 1], "-%u", &idx)))
386     slen--;
387   if (slen == 0)
388     return GNUNET_SYSERR;
389   name = GNUNET_strdup (ns_uname);
390   name[slen - 1] = '\0';
391   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
392   GNUNET_free (name);
393   fn = get_data_filename (cfg, PS_NAMES_DIR, &nh);
394   GNUNET_assert (fn != NULL);
395
396   if ((GNUNET_OK != GNUNET_DISK_file_test (fn) ||
397        (GNUNET_OK != GNUNET_DISK_file_size (fn, &len, GNUNET_YES))) ||
398       ((idx + 1) * sizeof (GNUNET_HashCode) > len))
399     {
400       GNUNET_free (fn);
401       return GNUNET_SYSERR;
402     }
403   fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_CREATE
404                               | GNUNET_DISK_OPEN_READWRITE,
405                               GNUNET_DISK_PERM_USER_READ |
406                               GNUNET_DISK_PERM_USER_WRITE);
407   GNUNET_free (fn);
408   GNUNET_DISK_file_seek (fh, idx * sizeof (GNUNET_HashCode),
409                          GNUNET_DISK_SEEK_SET);
410   if (sizeof (GNUNET_HashCode) !=
411       GNUNET_DISK_file_read (fh, nsid, sizeof (GNUNET_HashCode)))
412     {
413       GNUNET_DISK_file_close (fh);
414       return GNUNET_SYSERR;
415     }
416   GNUNET_DISK_file_close (fh);
417   return GNUNET_OK;
418 }
419
420
421
422 /**
423  * struct used to list the pseudonym
424  */
425 struct ListPseudonymClosure
426 {
427
428   /**
429    * iterator over pseudonym
430    */
431   GNUNET_PSEUDONYM_Iterator iterator;
432
433   /**
434    * Closure for iterator.
435    */
436   void *closure;
437
438   /**
439    * Configuration to use.
440    */
441   const struct GNUNET_CONFIGURATION_Handle *cfg;
442 };
443
444
445
446 /**
447  * the help function to list all available pseudonyms
448  * @param cls point to a struct ListPseudonymClosure
449  * @param fullname name of pseudonym
450  */
451 static int
452 list_pseudonym_helper (void *cls, const char *fullname)
453 {
454   struct ListPseudonymClosure *c = cls;
455   int ret;
456   GNUNET_HashCode id;
457   int rating;
458   struct GNUNET_CONTAINER_MetaData *meta;
459   const char *fn;
460   char *str;
461
462   if (strlen (fullname) < sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded))
463     return GNUNET_OK;
464   fn =
465     &fullname[strlen (fullname) + 1 -
466               sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)];
467   if (fn[-1] != DIR_SEPARATOR)
468     return GNUNET_OK;
469   ret = GNUNET_OK;
470   if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (fn, &id))
471     return GNUNET_OK;           /* invalid name */
472   str = NULL;
473   if (GNUNET_OK != read_info (c->cfg, &id, &meta, &rating, &str))
474     return GNUNET_OK;           /* ignore entry */
475   GNUNET_free_non_null (str);
476   if (c->iterator != NULL)
477     ret = c->iterator (c->closure, &id, meta, rating);
478   GNUNET_CONTAINER_meta_data_destroy (meta);
479   return ret;
480 }
481
482
483 /**
484  * List all available pseudonyms.
485  *
486  * @param cfg overall configuration 
487  * @param iterator function to call for each pseudonym
488  * @param closure closure for iterator
489  * @return number of pseudonyms found
490  */
491 int
492 GNUNET_PSEUDONYM_list_all (const struct GNUNET_CONFIGURATION_Handle *cfg,
493                            GNUNET_PSEUDONYM_Iterator iterator, void *closure)
494 {
495   struct ListPseudonymClosure cls;
496   char *fn;
497   int ret;
498
499   cls.iterator = iterator;
500   cls.closure = closure;
501   cls.cfg = cfg;
502   fn = get_data_filename (cfg, PS_METADATA_DIR, NULL);
503   GNUNET_assert (fn != NULL);
504   GNUNET_DISK_directory_create (fn);
505   ret = GNUNET_DISK_directory_scan (fn, &list_pseudonym_helper, &cls);
506   GNUNET_free (fn);
507   return ret;
508 }
509
510
511 /**
512  * Change the ranking of a pseudonym.
513  *
514  * @param cfg overall configuration
515  * @param nsid id of the pseudonym
516  * @param delta by how much should the rating be
517  *  changed?
518  * @return new rating of the pseudonym
519  */
520 int
521 GNUNET_PSEUDONYM_rank (const struct GNUNET_CONFIGURATION_Handle *cfg,
522                        const GNUNET_HashCode * nsid, int delta)
523 {
524   struct GNUNET_CONTAINER_MetaData *meta;
525   int ret;
526   int32_t ranking;
527   char *name;
528
529   name = NULL;
530   ret = read_info (cfg, nsid, &meta, &ranking, &name);
531   if (ret == GNUNET_SYSERR)
532     {
533       ranking = 0;
534       meta = GNUNET_CONTAINER_meta_data_create ();
535     }
536   ranking += delta;
537   write_pseudonym_info (cfg, nsid, meta, ranking, name);
538   GNUNET_CONTAINER_meta_data_destroy (meta);
539   GNUNET_free_non_null (name);
540   return ranking;
541 }
542
543
544 /**
545  * Add a pseudonym to the set of known pseudonyms.
546  * For all pseudonym advertisements that we discover
547  * FS should automatically call this function.
548  *
549  * @param cfg overall configuration
550  * @param id the pseudonym identifier
551  * @param meta metadata for the pseudonym
552  */
553 void
554 GNUNET_PSEUDONYM_add (const struct GNUNET_CONFIGURATION_Handle *cfg,
555                       const GNUNET_HashCode * id,
556                       const struct GNUNET_CONTAINER_MetaData *meta)
557 {
558   char *name;
559   int32_t ranking;
560   struct GNUNET_CONTAINER_MetaData *old;
561   char *fn;
562   struct stat sbuf;
563
564   ranking = 0;
565   fn = get_data_filename (cfg, PS_METADATA_DIR, id);
566   GNUNET_assert (fn != NULL);
567
568   if ((0 == STAT (fn, &sbuf)) &&
569       (GNUNET_OK == read_info (cfg, id, &old, &ranking, &name)))
570     {
571       GNUNET_CONTAINER_meta_data_merge (old, meta);
572       write_pseudonym_info (cfg, id, old, ranking, name);
573       GNUNET_CONTAINER_meta_data_destroy (old);
574       GNUNET_free_non_null (name);
575     }
576   else
577     {
578       write_pseudonym_info (cfg, id, meta, ranking, NULL);
579     }
580   GNUNET_free (fn);
581   internal_notify (id, meta, ranking);
582 }
583
584
585 /* end of pseudonym.c */