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