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