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