- fix
[oweals/gnunet.git] / src / util / pseudonym.c
1 /*
2      This file is part of GNUnet
3      (C) 2003, 2004, 2005, 2006, 2007, 2008, 2013 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  * @file util/pseudonym.c
22  * @brief helper functions
23  * @author Christian Grothoff
24  *
25  * TODO:
26  * - all cryptographic operations are currently NOT implemented and
27  *   provided by stubs that merely pretend to work!
28  */
29 #include "platform.h"
30 #include "gnunet_common.h"
31 #include "gnunet_container_lib.h"
32 #include "gnunet_disk_lib.h"
33 #include "gnunet_pseudonym_lib.h"
34 #include "gnunet_bio_lib.h"
35 #include <gcrypt.h>
36
37 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
38
39 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
40
41 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42
43 /**
44  * Log an error message at log-level 'level' that indicates
45  * a failure of the command 'cmd' with the message given
46  * by gcry_strerror(rc).
47  */
48 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0);
49
50 /**
51  * Name of the directory which stores meta data for pseudonym
52  */
53 #define PS_METADATA_DIR DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonym" DIR_SEPARATOR_STR "metadata" DIR_SEPARATOR_STR
54
55 /**
56  * Name of the directory which stores names for pseudonyms
57  */
58 #define PS_NAMES_DIR    DIR_SEPARATOR_STR "data" DIR_SEPARATOR_STR "pseudonym" DIR_SEPARATOR_STR "names"    DIR_SEPARATOR_STR
59
60
61 /**
62  * Configuration section we use.
63  */
64 #define GNUNET_CLIENT_SERVICE_NAME "client"
65
66
67 /* ************************* Disk operations (pseudonym data mgmt) **************** */
68
69 /**
70  * Registered callbacks for discovery of pseudonyms.
71  */
72 struct GNUNET_PSEUDONYM_DiscoveryHandle
73 {
74   /**
75    * This is a doubly linked list.
76    */
77   struct GNUNET_PSEUDONYM_DiscoveryHandle *next;
78
79   /**
80    * This is a doubly linked list.
81    */
82   struct GNUNET_PSEUDONYM_DiscoveryHandle *prev;
83
84   /**
85    * Function to call each time a pseudonym is discovered.
86    */
87   GNUNET_PSEUDONYM_Iterator callback;
88
89   /**
90    * Closure for callback.
91    */
92   void *callback_cls;
93 };
94
95
96 /**
97  * Head of the linked list of functions to call when
98  * new pseudonyms are added.
99  */
100 static struct GNUNET_PSEUDONYM_DiscoveryHandle *disco_head;
101
102 /**
103  * Tail of the linked list of functions to call when
104  * new pseudonyms are added.
105  */
106 static struct GNUNET_PSEUDONYM_DiscoveryHandle *disco_tail;
107
108
109 /**
110  * Internal notification about new tracked URI.
111  *
112  * @param pseudonym public key of the pseudonym
113  * @param md meta data to be written
114  * @param rating rating of pseudonym
115  */
116 static void
117 internal_notify (const struct GNUNET_PseudonymIdentifier *pseudonym,
118                  const struct GNUNET_CONTAINER_MetaData *md, int rating)
119 {
120   struct GNUNET_PSEUDONYM_DiscoveryHandle *pos;
121
122   for (pos = disco_head; NULL != pos; pos = pos->next)
123     pos->callback (pos->callback_cls, pseudonym, NULL, NULL, md, rating);
124 }
125
126
127 /**
128  * Register callback to be invoked whenever we discover
129  * a new pseudonym.
130  * Will immediately call provided iterator callback for all
131  * already discovered pseudonyms.
132  *
133  * @param cfg configuration to use
134  * @param iterator iterator over pseudonym
135  * @param iterator_cls point to a closure
136  * @return registration handle
137  */
138 struct GNUNET_PSEUDONYM_DiscoveryHandle *
139 GNUNET_PSEUDONYM_discovery_callback_register (const struct
140                                               GNUNET_CONFIGURATION_Handle *cfg,
141                                               GNUNET_PSEUDONYM_Iterator iterator, 
142                                               void *iterator_cls)
143 {
144   struct GNUNET_PSEUDONYM_DiscoveryHandle *dh;
145
146   dh = GNUNET_malloc (sizeof (struct GNUNET_PSEUDONYM_DiscoveryHandle));
147   dh->callback = iterator;
148   dh->callback_cls = iterator_cls;
149   GNUNET_CONTAINER_DLL_insert (disco_head, disco_tail, dh);
150   GNUNET_PSEUDONYM_list_all (cfg, iterator, iterator_cls);
151   return dh;
152 }
153
154
155 /**
156  * Unregister pseudonym discovery callback.
157  *
158  * @param dh registration to unregister
159  */
160 void
161 GNUNET_PSEUDONYM_discovery_callback_unregister (struct GNUNET_PSEUDONYM_DiscoveryHandle *dh)
162 {
163   GNUNET_CONTAINER_DLL_remove (disco_head, disco_tail, dh);
164   GNUNET_free (dh);
165 }
166
167
168 /**
169  * Get the filename (or directory name) for the given
170  * pseudonym identifier and directory prefix.
171  *
172  * @param cfg configuration to use
173  * @param prefix path components to append to the private directory name
174  * @param pseudonym the pseudonym, can be NULL
175  * @return filename of the pseudonym (if pseudonym != NULL) or directory with the data (if pseudonym == NULL)
176  */
177 static char *
178 get_data_filename (const struct GNUNET_CONFIGURATION_Handle *cfg,
179                    const char *prefix, 
180                    const struct GNUNET_PseudonymIdentifier *pseudonym)
181 {
182   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
183   struct GNUNET_HashCode psid;
184
185   if (NULL != pseudonym)
186   {
187     GNUNET_CRYPTO_hash (pseudonym,
188                         sizeof (struct GNUNET_PseudonymIdentifier),
189                         &psid);
190     GNUNET_CRYPTO_hash_to_enc (&psid, &enc);
191   }
192   return GNUNET_DISK_get_home_filename (cfg, 
193                                         GNUNET_CLIENT_SERVICE_NAME, prefix,
194                                         (NULL == pseudonym) 
195                                         ? NULL 
196                                         : (const char *) &enc,
197                                         NULL);
198 }
199
200
201 /**
202  * Get the filename (or directory name) for the given
203  * hash code and directory prefix.
204  *
205  * @param cfg configuration to use
206  * @param prefix path components to append to the private directory name
207  * @param hc some hash code
208  * @return filename of the pseudonym (if hc != NULL) or directory with the data (if hc == NULL)
209  */
210 static char *
211 get_data_filename_hash (const struct GNUNET_CONFIGURATION_Handle *cfg,
212                         const char *prefix, 
213                         const struct GNUNET_HashCode *hc)
214 {
215   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
216
217   if (NULL != hc)
218     GNUNET_CRYPTO_hash_to_enc (hc, &enc);
219   return GNUNET_DISK_get_home_filename (cfg, 
220                                         GNUNET_CLIENT_SERVICE_NAME, prefix,
221                                         (NULL == hc) 
222                                         ? NULL 
223                                         : (const char *) &enc,
224                                         NULL);
225 }
226
227
228 /**
229  * Set the pseudonym metadata, rank and name.
230  * Writes the pseudonym infomation into a file
231  *
232  * @param cfg overall configuration
233  * @param pseudonym id of the pseudonym
234  * @param name name to set. Must be the non-unique version of it.
235  *        May be NULL, in which case it erases pseudonym's name!
236  * @param md metadata to set
237  *        May be NULL, in which case it erases pseudonym's metadata!
238  * @param rank rank to assign
239  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
240  */
241 int
242 GNUNET_PSEUDONYM_set_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
243                            const struct GNUNET_PseudonymIdentifier *pseudonym,
244                            const char *name,
245                            const struct GNUNET_CONTAINER_MetaData *md, 
246                            int32_t rank)
247 {
248   char *fn;
249   struct GNUNET_BIO_WriteHandle *fileW;
250
251   fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
252   if (NULL == (fileW = GNUNET_BIO_write_open (fn)))
253   {
254     GNUNET_free (fn);
255     return GNUNET_SYSERR;
256   }
257   if ((GNUNET_OK != GNUNET_BIO_write (fileW, pseudonym, 
258                                       sizeof (struct GNUNET_PseudonymIdentifier))) ||
259       (GNUNET_OK != GNUNET_BIO_write_int32 (fileW, rank)) ||
260       (GNUNET_OK != GNUNET_BIO_write_string (fileW, name)) ||
261       (GNUNET_OK != GNUNET_BIO_write_meta_data (fileW, md)))
262   {
263     (void) GNUNET_BIO_write_close (fileW);
264     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
265     GNUNET_free (fn);
266     return GNUNET_SYSERR;
267   }
268   if (GNUNET_OK != GNUNET_BIO_write_close (fileW))
269   {
270     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
271     GNUNET_free (fn);
272     return GNUNET_SYSERR;
273   } 
274   GNUNET_free (fn);
275   /* create entry for pseudonym name in names */
276   if (NULL != name)
277     GNUNET_free_non_null (GNUNET_PSEUDONYM_name_uniquify (cfg, pseudonym, 
278                                                           name, NULL));
279   return GNUNET_OK;
280 }
281
282
283 /**
284  * Read pseudonym infomation from a file
285  *
286  * @param cfg configuration to use
287  * @param pseudonym hash code of a pseudonym
288  * @param meta meta data to be read from a file
289  * @param rank rank of a pseudonym
290  * @param ns_name name of a pseudonym
291  * @return GNUNET_OK on success, GNUNET_SYSERR on error
292  */
293 static int
294 read_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
295            const struct GNUNET_PseudonymIdentifier *pseudonym,
296            struct GNUNET_CONTAINER_MetaData **meta,
297            int32_t *rank,
298            char **ns_name)
299 {
300   struct GNUNET_PseudonymIdentifier pd;
301   char *fn;
302   char *emsg;
303   struct GNUNET_BIO_ReadHandle *fileR;
304
305   fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
306   if (GNUNET_YES !=
307       GNUNET_DISK_file_test (fn))
308   {
309     GNUNET_free (fn);
310     return GNUNET_SYSERR;
311   }
312   if (NULL == (fileR = GNUNET_BIO_read_open (fn)))
313   {
314     GNUNET_free (fn);
315     return GNUNET_SYSERR;
316   }
317   emsg = NULL;
318   *ns_name = NULL;
319   if ( (GNUNET_OK != GNUNET_BIO_read (fileR, "pseudonym", &pd, sizeof (pd))) ||
320        (0 != memcmp (&pd, pseudonym, sizeof (pd))) ||
321        (GNUNET_OK != GNUNET_BIO_read_int32 (fileR, rank)) ||
322        (GNUNET_OK !=
323         GNUNET_BIO_read_string (fileR, "Read string error!", ns_name, 200)) ||
324        (GNUNET_OK !=
325        GNUNET_BIO_read_meta_data (fileR, "Read meta data error!", meta)) )
326   {
327     (void) GNUNET_BIO_read_close (fileR, &emsg);
328     GNUNET_free_non_null (emsg);
329     GNUNET_free_non_null (*ns_name);
330     *ns_name = NULL;
331     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
332     GNUNET_free (fn);
333     return GNUNET_SYSERR;
334   }
335   if (GNUNET_OK != GNUNET_BIO_read_close (fileR, &emsg))
336   {
337     LOG (GNUNET_ERROR_TYPE_WARNING,
338          _("Failed to parse metadata about pseudonym from file `%s': %s\n"), fn,
339          emsg);
340     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fn));
341     GNUNET_CONTAINER_meta_data_destroy (*meta);
342     *meta = NULL;
343     GNUNET_free_non_null (*ns_name);
344     *ns_name = NULL;
345     GNUNET_free_non_null (emsg);
346     GNUNET_free (fn);
347     return GNUNET_SYSERR;
348   }
349   GNUNET_free (fn);
350   return GNUNET_OK;
351 }
352
353
354 /**
355  * Return unique variant of the namespace name.  Use it after
356  * GNUNET_PSEUDONYM_get_info() to make sure that name is unique.
357  *
358  * @param cfg configuration
359  * @param pseudonym public key of the pseudonym
360  * @param name name to uniquify
361  * @param suffix if not NULL, filled with the suffix value
362  * @return NULL on failure (should never happen), name on success.
363  *         Free the name with GNUNET_free().
364  */
365 char *
366 GNUNET_PSEUDONYM_name_uniquify (const struct GNUNET_CONFIGURATION_Handle *cfg,
367                                 const struct GNUNET_PseudonymIdentifier *pseudonym,
368                                 const char *name,
369                                 unsigned int *suffix)
370 {
371   struct GNUNET_HashCode nh;
372   struct GNUNET_PseudonymIdentifier pi;
373   uint64_t len;
374   char *fn;
375   struct GNUNET_DISK_FileHandle *fh;
376   unsigned int i;
377   unsigned int idx;
378   char *ret;
379   struct stat sbuf;
380
381   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
382   fn = get_data_filename_hash (cfg, PS_NAMES_DIR, &nh);
383   len = 0;
384   if (0 == STAT (fn, &sbuf))
385     GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (fn, &len, GNUNET_YES, GNUNET_YES));
386   fh = GNUNET_DISK_file_open (fn,
387                               GNUNET_DISK_OPEN_CREATE |
388                               GNUNET_DISK_OPEN_READWRITE,
389                               GNUNET_DISK_PERM_USER_READ |
390                               GNUNET_DISK_PERM_USER_WRITE);
391   i = 0;
392   idx = -1;
393   while ((len >= sizeof (struct GNUNET_PseudonymIdentifier)) &&
394          (sizeof (struct GNUNET_PseudonymIdentifier) ==
395           GNUNET_DISK_file_read (fh, &pi, sizeof (struct GNUNET_PseudonymIdentifier))))
396   {
397     if (0 == memcmp (&pi, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
398     {
399       idx = i;
400       break;
401     }
402     i++;
403     len -= sizeof (struct GNUNET_HashCode);
404   }
405   if (-1 == idx)
406   {
407     idx = i;
408     if (sizeof (struct GNUNET_PseudonymIdentifier) !=
409         GNUNET_DISK_file_write (fh, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
410       LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "write", fn);
411   }
412   GNUNET_DISK_file_close (fh);
413   ret = GNUNET_malloc (strlen (name) + 32);
414   GNUNET_snprintf (ret, strlen (name) + 32, "%s-%u", name, idx);
415   if (suffix != NULL)
416     *suffix = idx;
417   GNUNET_free (fn);
418   return ret;
419 }
420
421
422 /**
423  * Get namespace name, metadata and rank
424  * This is a wrapper around internal read_info() call, and ensures that
425  * returned data is not invalid (not NULL).
426  *
427  * @param cfg configuration
428  * @param pseudonym public key of the pseudonym
429  * @param ret_meta a location to store metadata pointer. NULL, if metadata
430  *        is not needed. Destroy with GNUNET_CONTAINER_meta_data_destroy().
431  * @param ret_rank a location to store rank. NULL, if rank not needed.
432  * @param ret_name a location to store human-readable name. Name is not unique.
433  *        NULL, if name is not needed. Free with GNUNET_free().
434  * @param name_is_a_dup is set to GNUNET_YES, if ret_name was filled with
435  *        a duplicate of a "no-name" placeholder
436  * @return GNUNET_OK on success. GNUENT_SYSERR if the data was
437  *         unobtainable (in that case ret_* are filled with placeholders - 
438  *         empty metadata container, rank -1 and a "no-name" name).
439  */
440 int
441 GNUNET_PSEUDONYM_get_info (const struct GNUNET_CONFIGURATION_Handle *cfg,
442                            const struct GNUNET_PseudonymIdentifier *pseudonym, 
443                            struct GNUNET_CONTAINER_MetaData **ret_meta,
444                            int32_t *ret_rank, 
445                            char **ret_name, 
446                            int *name_is_a_dup)
447 {
448   struct GNUNET_CONTAINER_MetaData *meta;
449   char *name;
450   int32_t rank = -1;
451
452   meta = NULL;
453   name = NULL;
454   if (GNUNET_OK == read_info (cfg, pseudonym, &meta, &rank, &name))
455   {
456     if ((meta != NULL) && (name == NULL))
457       name =
458           GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
459                                                          EXTRACTOR_METATYPE_TITLE,
460                                                          EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
461                                                          EXTRACTOR_METATYPE_FILENAME,
462                                                          EXTRACTOR_METATYPE_DESCRIPTION,
463                                                          EXTRACTOR_METATYPE_SUBJECT,
464                                                          EXTRACTOR_METATYPE_PUBLISHER,
465                                                          EXTRACTOR_METATYPE_AUTHOR_NAME,
466                                                          EXTRACTOR_METATYPE_COMMENT,
467                                                          EXTRACTOR_METATYPE_SUMMARY,
468                                                          -1);
469     if (ret_name != NULL)
470     {
471       if (name == NULL)
472       {
473         name = GNUNET_strdup (_("no-name"));
474         if (name_is_a_dup != NULL)
475           *name_is_a_dup = GNUNET_YES;
476       }
477       else if (name_is_a_dup != NULL)
478         *name_is_a_dup = GNUNET_NO;
479       *ret_name = name;
480     }
481     else if (name != NULL)
482       GNUNET_free (name);
483
484     if (ret_meta != NULL)
485     {
486       if (meta == NULL)
487         meta = GNUNET_CONTAINER_meta_data_create ();
488       *ret_meta = meta;
489     }
490     else if (meta != NULL)
491       GNUNET_CONTAINER_meta_data_destroy (meta);
492
493     if (ret_rank != NULL)
494       *ret_rank = rank;
495
496     return GNUNET_OK;
497   }
498   if (ret_name != NULL)
499     *ret_name = GNUNET_strdup (_("no-name"));
500   if (ret_meta != NULL)
501     *ret_meta = GNUNET_CONTAINER_meta_data_create ();
502   if (ret_rank != NULL)
503     *ret_rank = -1;
504   if (name_is_a_dup != NULL)
505     *name_is_a_dup = GNUNET_YES;
506   return GNUNET_SYSERR;
507 }
508
509
510 /**
511  * Get the namespace ID belonging to the given namespace name.
512  *
513  * @param cfg configuration to use
514  * @param ns_uname unique (!) human-readable name for the namespace
515  * @param pseudonym set to public key of pseudonym based on 'ns_uname'
516  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
517  */
518 int
519 GNUNET_PSEUDONYM_name_to_id (const struct GNUNET_CONFIGURATION_Handle *cfg,
520                              const char *ns_uname, 
521                              struct GNUNET_PseudonymIdentifier *pseudonym)
522 {
523   size_t slen;
524   uint64_t len;
525   unsigned int idx;
526   char *name;
527   struct GNUNET_HashCode nh;
528   char *fn;
529   struct GNUNET_DISK_FileHandle *fh;
530
531   idx = -1;
532   slen = strlen (ns_uname);
533   while ((slen > 0) && (1 != SSCANF (&ns_uname[slen - 1], "-%u", &idx)))
534     slen--;
535   if (0 == slen)
536     return GNUNET_SYSERR;
537   name = GNUNET_strdup (ns_uname);
538   name[slen - 1] = '\0';
539
540   GNUNET_CRYPTO_hash (name, strlen (name), &nh);
541   GNUNET_free (name);
542   fn = get_data_filename_hash (cfg, PS_NAMES_DIR, &nh);
543
544   if ((GNUNET_OK != GNUNET_DISK_file_test (fn) ||
545        (GNUNET_OK != GNUNET_DISK_file_size (fn, &len, GNUNET_YES, GNUNET_YES))) ||
546       ((idx + 1) * sizeof (struct GNUNET_PseudonymIdentifier) > len))
547   {
548     GNUNET_free (fn);
549     return GNUNET_SYSERR;
550   }
551   fh = GNUNET_DISK_file_open (fn,
552                               GNUNET_DISK_OPEN_CREATE |
553                               GNUNET_DISK_OPEN_READWRITE,
554                               GNUNET_DISK_PERM_USER_READ |
555                               GNUNET_DISK_PERM_USER_WRITE);
556   GNUNET_free (fn);
557   if (GNUNET_SYSERR ==
558       GNUNET_DISK_file_seek (fh, idx * sizeof (struct GNUNET_PseudonymIdentifier),
559                              GNUNET_DISK_SEEK_SET))
560   {
561     GNUNET_DISK_file_close (fh);
562     return GNUNET_SYSERR;
563   }
564   if (sizeof (struct GNUNET_PseudonymIdentifier) !=
565       GNUNET_DISK_file_read (fh, pseudonym, sizeof (struct GNUNET_PseudonymIdentifier)))
566   {
567     GNUNET_DISK_file_close (fh);
568     return GNUNET_SYSERR;
569   }
570   GNUNET_DISK_file_close (fh);
571   return GNUNET_OK;
572 }
573
574
575
576 /**
577  * struct used to list the pseudonym
578  */
579 struct ListPseudonymClosure
580 {
581
582   /**
583    * iterator over pseudonym
584    */
585   GNUNET_PSEUDONYM_Iterator iterator;
586
587   /**
588    * Closure for iterator.
589    */
590   void *iterator_cls;
591
592   /**
593    * Configuration to use.
594    */
595   const struct GNUNET_CONFIGURATION_Handle *cfg;
596 };
597
598
599
600 /**
601  * Helper function to list all available pseudonyms
602  *
603  * @param cls point to a struct ListPseudonymClosure
604  * @param fullname name of pseudonym
605  */
606 static int
607 list_pseudonym_helper (void *cls, const char *fullname)
608 {
609   struct ListPseudonymClosure *lpc = cls;
610   struct GNUNET_PseudonymIdentifier pd;
611   char *emsg;
612   struct GNUNET_BIO_ReadHandle *fileR;
613   int32_t rank;
614   char *ns_name;
615   struct GNUNET_CONTAINER_MetaData *meta;
616   int ret; 
617   char *name_unique;
618
619   if (NULL == (fileR = GNUNET_BIO_read_open (fullname)))
620     return GNUNET_SYSERR;
621   emsg = NULL;
622   ns_name = NULL;
623   if ( (GNUNET_OK != GNUNET_BIO_read (fileR, "pseudonym", &pd, sizeof (pd))) ||
624        (GNUNET_OK != GNUNET_BIO_read_int32 (fileR, &rank)) ||
625        (GNUNET_OK !=
626         GNUNET_BIO_read_string (fileR, "Read string error!", &ns_name, 200)) ||
627        (GNUNET_OK !=
628        GNUNET_BIO_read_meta_data (fileR, "Read meta data error!", &meta)) )
629   {
630     (void) GNUNET_BIO_read_close (fileR, &emsg);
631     GNUNET_free_non_null (emsg);
632     GNUNET_free_non_null (ns_name);
633     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fullname));
634     return GNUNET_SYSERR;
635   }
636   if (NULL == ns_name)
637     ns_name = GNUNET_strdup (_("no-name"));
638   if (GNUNET_OK != GNUNET_BIO_read_close (fileR, &emsg))
639   {
640     LOG (GNUNET_ERROR_TYPE_WARNING,
641          _("Failed to parse metadata about pseudonym from file `%s': %s\n"), fullname,
642          emsg);
643     GNUNET_break (GNUNET_OK == GNUNET_DISK_directory_remove (fullname));
644     GNUNET_CONTAINER_meta_data_destroy (meta);
645     GNUNET_free (ns_name);
646     GNUNET_free_non_null (emsg);
647     return GNUNET_SYSERR;
648   }
649   ret = GNUNET_OK;
650   name_unique = GNUNET_PSEUDONYM_name_uniquify (lpc->cfg, &pd, ns_name, NULL);
651   if (NULL != lpc->iterator)
652     ret = lpc->iterator (lpc->iterator_cls, &pd, ns_name, name_unique, meta, rank);
653   GNUNET_free (ns_name);
654   GNUNET_free_non_null (name_unique);
655   GNUNET_CONTAINER_meta_data_destroy (meta);
656   return ret;
657 }
658
659
660 /**
661  * List all available pseudonyms.
662  *
663  * @param cfg overall configuration
664  * @param iterator function to call for each pseudonym
665  * @param iterator_cls closure for iterator
666  * @return number of pseudonyms found
667  */
668 int
669 GNUNET_PSEUDONYM_list_all (const struct GNUNET_CONFIGURATION_Handle *cfg,
670                            GNUNET_PSEUDONYM_Iterator iterator, 
671                            void *iterator_cls)
672 {
673   struct ListPseudonymClosure cls;
674   char *fn;
675   int ret;
676
677   cls.iterator = iterator;
678   cls.iterator_cls = iterator_cls;
679   cls.cfg = cfg;
680   fn = get_data_filename (cfg, PS_METADATA_DIR, NULL);
681   GNUNET_assert (fn != NULL);
682   GNUNET_DISK_directory_create (fn);
683   ret = GNUNET_DISK_directory_scan (fn, &list_pseudonym_helper, &cls);
684   GNUNET_free (fn);
685   return ret;
686 }
687
688
689 /**
690  * Change the rank of a pseudonym.
691  *
692  * @param cfg overall configuration
693  * @param pseudonym the pseudonym
694  * @param delta by how much should the rating be changed?
695  * @return new rating of the pseudonym
696  */
697 int
698 GNUNET_PSEUDONYM_rank (const struct GNUNET_CONFIGURATION_Handle *cfg,
699                        const struct GNUNET_PseudonymIdentifier *pseudonym, 
700                        int32_t delta)
701 {
702   struct GNUNET_CONTAINER_MetaData *meta;
703   int ret;
704   int32_t rank;
705   char *name;
706
707   name = NULL;
708   ret = read_info (cfg, pseudonym, &meta, &rank, &name);
709   if (ret == GNUNET_SYSERR)
710   {
711     rank = 0;
712     meta = GNUNET_CONTAINER_meta_data_create ();
713   }
714   rank += delta;
715   GNUNET_PSEUDONYM_set_info (cfg, pseudonym, name, meta, rank);
716   GNUNET_CONTAINER_meta_data_destroy (meta);
717   GNUNET_free_non_null (name);
718   return rank;
719 }
720
721
722 /**
723  * Add a pseudonym to the set of known pseudonyms.
724  * For all pseudonym advertisements that we discover
725  * FS should automatically call this function.
726  *
727  * @param cfg overall configuration
728  * @param pseudonym the pseudonym to add
729  * @param meta metadata for the pseudonym
730  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
731  */
732 int
733 GNUNET_PSEUDONYM_add (const struct GNUNET_CONFIGURATION_Handle *cfg,
734                       const struct GNUNET_PseudonymIdentifier *pseudonym,
735                       const struct GNUNET_CONTAINER_MetaData *meta)
736 {
737   char *name;
738   int32_t rank;
739   struct GNUNET_CONTAINER_MetaData *old;
740   char *fn;
741   struct stat sbuf;
742   int ret;
743
744   rank = 0;
745   fn = get_data_filename (cfg, PS_METADATA_DIR, pseudonym);
746   GNUNET_assert (fn != NULL);
747
748   if ((0 == STAT (fn, &sbuf)) &&
749       (GNUNET_OK == read_info (cfg, pseudonym, &old, &rank, &name)))
750   {
751     GNUNET_CONTAINER_meta_data_merge (old, meta);
752     ret = GNUNET_PSEUDONYM_set_info (cfg, pseudonym, name, old, rank);
753     GNUNET_CONTAINER_meta_data_destroy (old);
754     GNUNET_free_non_null (name);
755   }
756   else
757   {
758     ret = GNUNET_PSEUDONYM_set_info (cfg, pseudonym, NULL, meta, rank);
759   }
760   GNUNET_free (fn);
761   internal_notify (pseudonym, meta, rank);
762   return ret;
763 }
764
765
766 /* ***************************** cryptographic operations ************************* */
767
768 /**
769  * Handle for a pseudonym (private key).
770  */
771 struct GNUNET_PseudonymHandle
772 {
773   /**
774    * 256-bit 'd' secret value (mod 'n', where n is 256-bit for NIST P-256).
775    */
776   unsigned char d[256 / 8];
777
778   /**
779    * Public key corresponding to the private key.
780    */
781   struct GNUNET_PseudonymIdentifier public_key;
782 };
783
784
785 /**
786  * If target != size, move target bytes to the end of the size-sized
787  * buffer and zero out the first target-size bytes.
788  *
789  * @param buf original buffer
790  * @param size number of bytes in the buffer
791  * @param target target size of the buffer
792  */
793 static void
794 adjust (unsigned char *buf, size_t size, size_t target)
795 {
796   if (size < target)
797   {
798     memmove (&buf[target - size], buf, size);
799     memset (buf, 0, target - size);
800   }
801 }
802
803
804 /**
805  * Extract values from an S-expression.
806  *
807  * @param array where to store the result(s)
808  * @param sexp S-expression to parse
809  * @param topname top-level name in the S-expression that is of interest
810  * @param elems names of the elements to extract
811  * @return 0 on success
812  */
813 static int
814 key_from_sexp (gcry_mpi_t * array, gcry_sexp_t sexp, const char *topname,
815                const char *elems)
816 {
817   gcry_sexp_t list;
818   gcry_sexp_t l2;
819   const char *s;
820   unsigned int i;
821   unsigned int idx;
822
823   if (! (list = gcry_sexp_find_token (sexp, topname, 0)))
824     return 1;  
825   l2 = gcry_sexp_cadr (list);
826   gcry_sexp_release (list);
827   list = l2;
828   if (! list)  
829     return 2;
830   idx = 0;
831   for (s = elems; *s; s++, idx++)
832   {
833     if (! (l2 = gcry_sexp_find_token (list, s, 1)))
834     {
835       for (i = 0; i < idx; i++)
836       {
837         gcry_free (array[i]);
838         array[i] = NULL;
839       }
840       gcry_sexp_release (list);
841       return 3;                 /* required parameter not found */
842     }
843     array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
844     gcry_sexp_release (l2);
845     if (! array[idx])
846     {
847       for (i = 0; i < idx; i++)
848       {
849         gcry_free (array[i]);
850         array[i] = NULL;
851       }
852       gcry_sexp_release (list);
853       return 4;                 /* required parameter is invalid */
854     }
855   }
856   gcry_sexp_release (list);
857   return 0;
858 }
859
860
861 /**
862  * Create a pseudonym.
863  *
864  * @param filename name of the file to use for storage, NULL for in-memory only
865  * @return handle to the private key of the pseudonym
866  */
867 struct GNUNET_PseudonymHandle *
868 GNUNET_PSEUDONYM_create (const char *filename)
869 {
870   struct GNUNET_PseudonymHandle *ph;
871   ssize_t ret;
872   gcry_sexp_t r_key;
873   gcry_sexp_t params;
874   gcry_error_t rc;
875   gcry_mpi_t skey[2];
876   size_t size;
877
878   ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
879   if ( (NULL != filename) &&
880        (GNUNET_YES == GNUNET_DISK_file_test (filename)) )
881   {
882     ret = GNUNET_DISK_fn_read (filename, ph, 
883                                sizeof (struct GNUNET_PseudonymHandle));
884     /* Note: we don't do any validation here, maybe we should? */
885     if (sizeof (struct GNUNET_PseudonymHandle) == ret)
886       return ph;
887   }  
888   if (0 != (rc = gcry_sexp_build (&params, NULL,
889                                   "(genkey(ecdsa(curve \"NIST P-256\")))")))
890   {
891     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
892     return NULL;
893   }
894   if (0 != (rc = gcry_pk_genkey (&r_key, params)))
895   {
896     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
897     return NULL;
898   }
899   /* NOTE: treating a point as a normal MPI value; hopefully that works... */
900   rc = key_from_sexp (skey, r_key, "private-key", "dq");
901   if (0 != rc)
902     rc = key_from_sexp (skey, r_key, "private-key", "dq");
903   if (0 != rc)
904     rc = key_from_sexp (skey, r_key, "ecc", "dq");
905   gcry_sexp_release (r_key);
906   size = sizeof (ph->d);
907   GNUNET_assert (0 ==
908                  gcry_mpi_print (GCRYMPI_FMT_USG, ph->d, size, &size,
909                                  skey[0]));
910   adjust (ph->d, size, sizeof (ph->d));
911   size = sizeof (ph->public_key.q);  
912   GNUNET_assert (0 ==
913                  gcry_mpi_print (GCRYMPI_FMT_USG, ph->public_key.q, size, &size,
914                                  skey[1]));
915   adjust (ph->public_key.q, size, sizeof (ph->public_key.q));
916   gcry_mpi_release (skey[0]);
917   gcry_mpi_release (skey[1]);
918   if (NULL != filename)
919   {
920     ret = GNUNET_DISK_fn_write (filename, ph, sizeof (struct GNUNET_PseudonymHandle),
921                                 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
922     if (sizeof (struct GNUNET_PseudonymHandle) != ret)
923     {
924       GNUNET_free (ph);
925       return NULL;
926     }
927   }
928   return ph;
929 }
930
931
932 /**
933  * Create a pseudonym, from a file that must already exist.
934  *
935  * @param filename name of the file to use for storage, NULL for in-memory only
936  * @return handle to the private key of the pseudonym
937  */
938 struct GNUNET_PseudonymHandle *
939 GNUNET_PSEUDONYM_create_from_existing_file (const char *filename)
940 {
941   struct GNUNET_PseudonymHandle *ph;
942   ssize_t ret;
943
944   ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
945   ret = GNUNET_DISK_fn_read (filename, ph, 
946                              sizeof (struct GNUNET_PseudonymHandle));
947   if (sizeof (struct GNUNET_PseudonymHandle) != ret)
948   {
949     GNUNET_free (ph);
950     return NULL;
951   }
952   /* Note: we don't do any validation here; maybe we should? */
953   return ph;
954 }
955
956
957 /**
958  * Get the handle for the 'anonymous' pseudonym shared by all users.
959  * That pseudonym uses a fixed 'secret' for the private key; this
960  * construction is useful to make anonymous and pseudonymous APIs
961  * (and packets) indistinguishable on the network.  See #2564.
962  *
963  * @return handle to the (non-secret) private key of the 'anonymous' pseudonym
964  */
965 struct GNUNET_PseudonymHandle *
966 GNUNET_PSEUDONYM_get_anonymous_pseudonym_handle ()
967 {
968   struct GNUNET_PseudonymHandle *ph;
969
970   ph = GNUNET_malloc (sizeof (struct GNUNET_PseudonymHandle));
971   /* FIXME: if we use 'd=0' for the anonymous handle (as per#2564),
972      then I believe the public key should be also zero, as Q=0P=0.
973      However, libgcrypt's point representation is completely internal,
974      and treats a z-coordinate of zero as infinity, so we likely need
975      to set it to (0,0,1) internally --- or actually calculate Q=qP
976      explicitly.  Either way, we don't have an API to do so yet :-(.
977   */
978   GNUNET_break (0);
979   return ph;
980 }
981
982
983 /**
984  * Destroy a pseudonym handle.  Does NOT remove the private key from
985  * the disk.
986  *
987  * @param ph pseudonym handle to destroy
988  */
989 void
990 GNUNET_PSEUDONYM_destroy (struct GNUNET_PseudonymHandle *ph)
991 {
992   GNUNET_free (ph);
993 }
994
995
996 /**
997  * Convert the data specified in the given purpose argument to an
998  * S-expression suitable for signature operations.
999  *
1000  * @param purpose data to convert
1001  * @return converted s-expression
1002  */
1003 static gcry_sexp_t
1004 data_to_pkcs1 (const struct GNUNET_PseudonymSignaturePurpose *purpose)
1005 {
1006   struct GNUNET_CRYPTO_ShortHashCode hc;
1007   size_t bufSize;
1008   gcry_sexp_t data;
1009
1010   GNUNET_CRYPTO_short_hash (purpose, ntohl (purpose->size), &hc);
1011 #define FORMATSTRING "(4:data(5:flags3:raw)(5:value32:01234567890123456789012345678901))"
1012   bufSize = strlen (FORMATSTRING) + 1;
1013   {
1014     char buff[bufSize];
1015
1016     memcpy (buff, FORMATSTRING, bufSize);
1017     memcpy (&buff
1018             [bufSize -
1019              strlen
1020              ("01234567890123456789012345678901))")
1021              - 1], &hc, sizeof (struct GNUNET_CRYPTO_ShortHashCode));
1022     GNUNET_assert (0 == gcry_sexp_new (&data, buff, bufSize, 0));
1023   }
1024 #undef FORMATSTRING
1025   return data;
1026 }
1027
1028
1029 /**
1030  * Cryptographically sign some data with the pseudonym.
1031  *
1032  * @param ph private key used for signing (corresponds to 'x' in #2564)
1033  * @param purpose data to sign
1034  * @param seed hash of the plaintext of the data that we are signing, 
1035  *             used for deterministic PRNG for anonymous signing;
1036  *             corresponds to 'k' in section 2.7 of #2564
1037  * @param signing_key modifier to apply to the private key for signing;
1038  *                    corresponds to 'h' in section 2.3 of #2564.
1039  * @param signature where to store the signature
1040  * @return GNUNET_SYSERR on failure
1041  */
1042 int 
1043 GNUNET_PSEUDONYM_sign (struct GNUNET_PseudonymHandle *ph,
1044                        const struct GNUNET_PseudonymSignaturePurpose *purpose,
1045                        const struct GNUNET_HashCode *seed,
1046                        const struct GNUNET_HashCode *signing_key,
1047                        struct GNUNET_PseudonymSignature *signature)
1048 {
1049   size_t size;
1050   size_t erroff;
1051   gcry_mpi_t x;
1052   gcry_mpi_t k;
1053   gcry_mpi_t h;
1054   gcry_mpi_t d;
1055   gcry_mpi_t n; /* n from P-256 */
1056   gcry_sexp_t spriv;
1057   gcry_sexp_t data;
1058   gcry_sexp_t result;
1059   gcry_mpi_t rs[2];
1060   int rc;
1061
1062   /* get private key 'x' from pseudonym */
1063   size = sizeof (ph->d);
1064   if (0 != (rc = gcry_mpi_scan (&x, GCRYMPI_FMT_USG,
1065                                 &ph->d,
1066                                 size, &size)))
1067   {
1068     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1069     return GNUNET_SYSERR;
1070   }
1071   /* get 'h' value from signing key */
1072   size = sizeof (struct GNUNET_HashCode);
1073   if (0 != (rc = gcry_mpi_scan (&h, GCRYMPI_FMT_USG,
1074                                 signing_key,
1075                                 size, &size)))
1076   {
1077     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1078     gcry_mpi_release (x);
1079     return GNUNET_SYSERR;
1080   } 
1081   
1082   /* initialize 'n' from P-256; hex copied from libgcrypt code */
1083   if (0 != (rc = gcry_mpi_scan (&n, GCRYMPI_FMT_HEX, 
1084                                 "0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 0, NULL)))
1085   {
1086     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1087     gcry_mpi_release (x);
1088     gcry_mpi_release (h);
1089     return GNUNET_SYSERR;
1090   }
1091
1092   /* calculate d = x + h mod n */
1093   d = gcry_mpi_new (256);
1094   gcry_mpi_addm (d, x, h, n);
1095   gcry_mpi_release (x);
1096   gcry_mpi_release (h);
1097   gcry_mpi_release (n);
1098   
1099   /* now build sexpression with the signing key;
1100      NOTE: libgcrypt docs say that we should specify 'Q', but
1101      with the current API we cannot calculate Q=dP, so hopefully
1102      libgcrypt will derive it from 'd' for us... */
1103   if (0 != (rc = gcry_sexp_build (&spriv, &erroff,
1104                                   "(private-key(ecc(curve \"NIST P-256\")(d %m)))",
1105                                   d)))
1106   {
1107     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1108     gcry_mpi_release (d);
1109     return GNUNET_SYSERR;
1110   }
1111   gcry_mpi_release (d);
1112   /* prepare data for signing */
1113   data = data_to_pkcs1 (purpose);
1114   
1115   /* get 'k' value from seed, if available */
1116   if (NULL != seed)
1117   {
1118     size = sizeof (struct GNUNET_HashCode);
1119     if (0 != (rc = gcry_mpi_scan (&k, GCRYMPI_FMT_USG,
1120                                   seed,
1121                                   size, &size)))
1122     {
1123       LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1124       gcry_mpi_release (x);
1125       return GNUNET_SYSERR;
1126     }
1127   }
1128
1129   /* actually create signature */
1130   /* FIXME: need API to pass 'k' if 'seed' was non-NULL! */
1131   if (0 != (rc = gcry_pk_sign (&result, data, spriv)))
1132   {
1133     LOG (GNUNET_ERROR_TYPE_WARNING,
1134          _("ECC signing failed at %s:%d: %s\n"), __FILE__,
1135          __LINE__, gcry_strerror (rc));
1136     gcry_sexp_release (data);
1137     gcry_sexp_release (spriv);
1138     if (NULL != seed)
1139       gcry_mpi_release (k);
1140     memset (signature, 0, sizeof (struct GNUNET_PseudonymSignature));
1141     return GNUNET_SYSERR;
1142   }
1143   if (NULL != seed)
1144     gcry_mpi_release (k);
1145   gcry_sexp_release (data);
1146   gcry_sexp_release (spriv);
1147
1148   /* extract 'r' and 's' values from sexpression 'result' and store in 'signature';
1149      FIXME: libgcrypt does not document format of s-expression returned for ECC
1150      signatures; so "ecc" here is just a guess. */
1151   if (0 != (rc = key_from_sexp (rs, result, "ecc", "rs")))
1152   {
1153     GNUNET_break (0);
1154     gcry_sexp_release (result);
1155     return GNUNET_SYSERR;
1156   }
1157   gcry_sexp_release (result);
1158   size = sizeof (signature->sig_r);
1159   if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) signature->sig_r, size,
1160                                  &size, rs[0])))
1161   {
1162     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
1163     gcry_mpi_release (rs[0]);
1164     gcry_mpi_release (rs[1]);
1165     return GNUNET_SYSERR;
1166   }
1167   gcry_mpi_release (rs[0]);
1168   size = sizeof (signature->sig_s);
1169   if (0 != (rc = gcry_mpi_print (GCRYMPI_FMT_USG, (unsigned char *) signature->sig_s, size,
1170                                  &size, rs[1])))
1171   {
1172     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_print", rc);
1173     gcry_mpi_release (rs[1]);
1174     return GNUNET_SYSERR;
1175   }
1176   gcry_mpi_release (rs[1]);
1177   return GNUNET_OK;
1178 }
1179
1180
1181 /**
1182  * Given a pseudonym and a signing key, derive the corresponding public
1183  * key that would be used to verify the resulting signature.
1184  *
1185  * @param pseudonym the public key (g^x in DSA, dQ in ECDSA)
1186  * @param signing_key input to derive 'h' (see section 2.4 of #2564)
1187  * @param verification_key resulting public key to verify the signature
1188  *        created from the 'ph' of 'pseudonym' and the 'signing_key';
1189  *        the value stored here can then be given to GNUNET_PSEUDONYM_verify.
1190  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1191  */
1192 int
1193 GNUNET_PSEUDONYM_derive_verification_key (struct GNUNET_PseudonymIdentifier *pseudonym,
1194                                           const struct GNUNET_HashCode *signing_key,
1195                                           struct GNUNET_PseudonymIdentifier *verification_key)
1196 {
1197   struct GNUNET_HashCode hc;
1198   struct GNUNET_HashCode x;
1199   gcry_mpi_t h;  
1200   size_t size;
1201   int rc;
1202
1203   /* get 'h' value from signing key */
1204   size = sizeof (struct GNUNET_HashCode);
1205   if (0 != (rc = gcry_mpi_scan (&h, GCRYMPI_FMT_USG,
1206                                 signing_key,
1207                                 size, &size)))
1208   {
1209     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1210     return GNUNET_SYSERR;
1211   }
1212   /* FIXME: calculate hQ --- need point multiplication API! */
1213   gcry_mpi_release (h);
1214   /* FIXME: calculate V = dQ + hQ --- need point addition API! */
1215   
1216   GNUNET_break (0);
1217   GNUNET_CRYPTO_hash (pseudonym, sizeof (*pseudonym), &hc);
1218   GNUNET_CRYPTO_hash_xor (&hc, signing_key, &x);  
1219   memset (verification_key, 0, sizeof (struct GNUNET_PseudonymIdentifier));
1220   memcpy (verification_key, &x, GNUNET_MIN (sizeof (x), sizeof (*verification_key)));
1221   return GNUNET_OK;
1222 }
1223
1224
1225 /**
1226  * Verify a signature made with a pseudonym.
1227  *
1228  * @param purpose data that was signed
1229  * @param signature signature to verify
1230  * @param verification_key public key to use for checking the signature;
1231  *                    corresponds to 'g^(x+h)' in section 2.4 of #2564.
1232  * @return GNUNET_OK on success (signature valid, 'pseudonym' set),
1233  *         GNUNET_SYSERR if the signature is invalid
1234  */
1235 int
1236 GNUNET_PSEUDONYM_verify (const struct GNUNET_PseudonymSignaturePurpose *purpose,
1237                          const struct GNUNET_PseudonymSignature *signature,
1238                          const struct GNUNET_PseudonymIdentifier *verification_key)
1239 {
1240 #if FUTURE
1241   gcry_sexp_t data;
1242   gcry_sexp_t sig_sexpr;
1243   gcry_sexp_t pk_sexpr;
1244   size_t size;
1245   gcry_mpi_t r;
1246   gcry_mpi_t s;
1247   gcry_mpi_t q;
1248   size_t erroff;
1249   int rc;
1250
1251   /* build s-expression for signature */
1252   size = sizeof (signature->sig_r);
1253   if (0 != (rc = gcry_mpi_scan (&r, GCRYMPI_FMT_USG,
1254                                 signature->sig_r, size, &size)))
1255   {
1256     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1257     return GNUNET_SYSERR;
1258   }
1259   size = sizeof (signature->sig_s);
1260   if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG,
1261                                 signature->sig_s, size, &size)))
1262   {
1263     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1264     gcry_mpi_release (r);
1265     return GNUNET_SYSERR;
1266   }
1267   if (0 != (rc = gcry_sexp_build (&sig_sexpr, &erroff, "(sig-val(ecc(r %m)(s %m)))",
1268                                   r, s)))
1269   {
1270     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1271     gcry_mpi_release (r);
1272     gcry_mpi_release (s);
1273     return GNUNET_SYSERR;
1274   }
1275   gcry_mpi_release (r);
1276   gcry_mpi_release (s);
1277
1278   /* build s-expression for data that was signed */
1279   data = data_to_pkcs1 (purpose);
1280
1281   /* build s-expression for public key */
1282   /* NOTE: treating a point as a normal MPI value; hopefully that works... */
1283   size = sizeof (verification_key->q);
1284   if (0 != (rc = gcry_mpi_scan (&q, GCRYMPI_FMT_USG,
1285                                 verification_key->q, size, &size)))
1286   {
1287     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
1288     gcry_sexp_release (data);
1289     gcry_sexp_release (sig_sexpr);
1290     return GNUNET_SYSERR;
1291   }
1292   if (0 != (rc = gcry_sexp_build (&sig_sexpr, &erroff, "(public-key(ecc(curve \"NIST P-256\")(q %m)))",
1293                                   q)))
1294   {
1295     LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1296     gcry_mpi_release (q);
1297     gcry_sexp_release (data);
1298     gcry_sexp_release (sig_sexpr);
1299     return GNUNET_SYSERR;
1300   }
1301   gcry_mpi_release (q);
1302
1303   /* finally, verify the signature */
1304   rc = gcry_pk_verify (sig_sexpr, data, pk_sexpr);
1305   gcry_sexp_release (sig_sexpr);
1306   gcry_sexp_release (data);
1307   gcry_sexp_release (pk_sexpr);
1308   if (rc)
1309   {
1310     LOG (GNUNET_ERROR_TYPE_WARNING,
1311          _("RSA signature verification failed at %s:%d: %s\n"), __FILE__,
1312          __LINE__, gcry_strerror (rc));
1313     return GNUNET_SYSERR;
1314   }
1315 #else
1316   GNUNET_break (0);
1317 #endif
1318   return GNUNET_OK;
1319 }
1320
1321
1322 /**
1323  * Get the identifier (public key) of a pseudonym.
1324  *
1325  * @param ph pseudonym handle with the private key
1326  * @param pseudonym pseudonym identifier (set based on 'ph')
1327  */
1328 void
1329 GNUNET_PSEUDONYM_get_identifier (struct GNUNET_PseudonymHandle *ph,
1330                                  struct GNUNET_PseudonymIdentifier *pseudonym)
1331 {
1332   memcpy (pseudonym, &ph->public_key,
1333           sizeof (struct GNUNET_PseudonymIdentifier));
1334 }
1335
1336
1337 /**
1338  * Remove pseudonym from the set of known pseudonyms.
1339  *
1340  * @param cfg overall configuration
1341  * @param id the pseudonym identifier
1342  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1343  */
1344 int
1345 GNUNET_PSEUDONYM_remove (const struct GNUNET_CONFIGURATION_Handle *cfg,
1346                          const struct GNUNET_PseudonymIdentifier *id)
1347 {
1348   char *fn;
1349   int result;
1350
1351   fn = get_data_filename (cfg, PS_METADATA_DIR, id);
1352   if (NULL == fn)
1353     return GNUNET_SYSERR;
1354   result = UNLINK (fn);
1355   GNUNET_free (fn);  
1356   return (0 == result) ? GNUNET_OK : GNUNET_SYSERR;
1357 }
1358
1359 /* end of pseudonym.c */