Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / agent / trustlist.c
1 /* trustlist.c - Maintain the list of trusted keys
2  * Copyright (C) 2002, 2004, 2006, 2007, 2009,
3  *               2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <assert.h>
28 #include <unistd.h>
29 #include <sys/stat.h>
30 #include <npth.h>
31
32 #include "agent.h"
33 #include <assuan.h> /* fixme: need a way to avoid assuan calls here */
34 #include "../common/i18n.h"
35
36
37 /* A structure to store the information from the trust file. */
38 struct trustitem_s
39 {
40   struct
41   {
42     int disabled:1;       /* This entry is disabled.  */
43     int for_pgp:1;        /* Set by '*' or 'P' as first flag. */
44     int for_smime:1;      /* Set by '*' or 'S' as first flag. */
45     int relax:1;          /* Relax checking of root certificate
46                              constraints. */
47     int cm:1;             /* Use chain model for validation. */
48   } flags;
49   unsigned char fpr[20];  /* The binary fingerprint. */
50 };
51 typedef struct trustitem_s trustitem_t;
52
53 /* Malloced table and its allocated size with all trust items. */
54 static trustitem_t *trusttable;
55 static size_t trusttablesize;
56 /* A mutex used to protect the table. */
57 static npth_mutex_t trusttable_lock;
58
59
60 static const char headerblurb[] =
61 "# This is the list of trusted keys.  Comment lines, like this one, as\n"
62 "# well as empty lines are ignored.  Lines have a length limit but this\n"
63 "# is not a serious limitation as the format of the entries is fixed and\n"
64 "# checked by gpg-agent.  A non-comment line starts with optional white\n"
65 "# space, followed by the SHA-1 fingerpint in hex, followed by a flag\n"
66 "# which may be one of 'P', 'S' or '*' and optionally followed by a list of\n"
67 "# other flags.  The fingerprint may be prefixed with a '!' to mark the\n"
68 "# key as not trusted.  You should give the gpg-agent a HUP or run the\n"
69 "# command \"gpgconf --reload gpg-agent\" after changing this file.\n"
70 "\n\n"
71 "# Include the default trust list\n"
72 "include-default\n"
73 "\n";
74
75
76 /* This function must be called once to initialize this module.  This
77    has to be done before a second thread is spawned.  We can't do the
78    static initialization because Pth emulation code might not be able
79    to do a static init; in particular, it is not possible for W32. */
80 void
81 initialize_module_trustlist (void)
82 {
83   static int initialized;
84   int err;
85
86   if (!initialized)
87     {
88       err = npth_mutex_init (&trusttable_lock, NULL);
89       if (err)
90         log_fatal ("failed to init mutex in %s: %s\n", __FILE__,strerror (err));
91       initialized = 1;
92     }
93 }
94
95
96
97 \f
98 static void
99 lock_trusttable (void)
100 {
101   int err;
102
103   err = npth_mutex_lock (&trusttable_lock);
104   if (err)
105     log_fatal ("failed to acquire mutex in %s: %s\n", __FILE__, strerror (err));
106 }
107
108
109 static void
110 unlock_trusttable (void)
111 {
112   int err;
113
114   err = npth_mutex_unlock (&trusttable_lock);
115   if (err)
116     log_fatal ("failed to release mutex in %s: %s\n", __FILE__, strerror (err));
117 }
118
119
120 /* Clear the trusttable.  The caller needs to make sure that the
121    trusttable is locked.  */
122 static inline void
123 clear_trusttable (void)
124 {
125   xfree (trusttable);
126   trusttable = NULL;
127   trusttablesize = 0;
128 }
129
130
131 /* Return the name of the system trustlist.  Caller must free.  */
132 static char *
133 make_sys_trustlist_name (void)
134 {
135   if (opt.sys_trustlist_name
136       && (strchr (opt.sys_trustlist_name, '/')
137           || strchr (opt.sys_trustlist_name, '\\')
138           || (*opt.sys_trustlist_name == '~'
139               && opt.sys_trustlist_name[1] == '/')))
140     return make_absfilename (opt.sys_trustlist_name, NULL);
141   else
142     return make_filename (gnupg_sysconfdir (),
143                           (opt.sys_trustlist_name ?
144                            opt.sys_trustlist_name : "trustlist.txt"),
145                           NULL);
146 }
147
148
149 static gpg_error_t
150 read_one_trustfile (const char *fname, int systrust,
151                     trustitem_t **addr_of_table,
152                     size_t *addr_of_tablesize,
153                     int *addr_of_tableidx)
154 {
155   gpg_error_t err = 0;
156   estream_t fp;
157   int n, c;
158   char *p, line[256];
159   trustitem_t *table, *ti;
160   int tableidx;
161   size_t tablesize;
162   int lnr = 0;
163
164   table = *addr_of_table;
165   tablesize = *addr_of_tablesize;
166   tableidx = *addr_of_tableidx;
167
168   fp = es_fopen (fname, "r");
169   if (!fp)
170     {
171       err = gpg_error_from_syserror ();
172       log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
173       goto leave;
174     }
175
176   while (es_fgets (line, DIM(line)-1, fp))
177     {
178       lnr++;
179
180       n = strlen (line);
181       if (!n || line[n-1] != '\n')
182         {
183           /* Eat until end of line. */
184           while ( (c=es_getc (fp)) != EOF && c != '\n')
185             ;
186           err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
187                            : GPG_ERR_INCOMPLETE_LINE);
188           log_error (_("file '%s', line %d: %s\n"),
189                      fname, lnr, gpg_strerror (err));
190           continue;
191         }
192       line[--n] = 0; /* Chop the LF. */
193       if (n && line[n-1] == '\r')
194         line[--n] = 0; /* Chop an optional CR. */
195
196       /* Allow for empty lines and spaces */
197       for (p=line; spacep (p); p++)
198         ;
199       if (!*p || *p == '#')
200         continue;
201
202       if (!strncmp (p, "include-default", 15)
203           && (!p[15] || spacep (p+15)))
204         {
205           char *etcname;
206           gpg_error_t err2;
207           gpg_err_code_t ec;
208
209           if (systrust)
210             {
211               log_error (_("statement \"%s\" ignored in '%s', line %d\n"),
212                          "include-default", fname, lnr);
213               continue;
214             }
215           /* fixme: Should check for trailing garbage.  */
216
217           etcname = make_sys_trustlist_name ();
218           if ( !strcmp (etcname, fname) ) /* Same file. */
219             log_info (_("statement \"%s\" ignored in '%s', line %d\n"),
220                       "include-default", fname, lnr);
221           else if ((ec=gnupg_access (etcname, F_OK)) && ec == GPG_ERR_ENOENT)
222             {
223               /* A non existent system trustlist is not an error.
224                  Just print a note. */
225               log_info (_("system trustlist '%s' not available\n"), etcname);
226             }
227           else
228             {
229               err2 = read_one_trustfile (etcname, 1,
230                                          &table, &tablesize, &tableidx);
231               if (err2)
232                 err = err2;
233             }
234           xfree (etcname);
235
236           continue;
237         }
238
239       if (tableidx == tablesize)  /* Need more space. */
240         {
241           trustitem_t *tmp;
242           size_t tmplen;
243
244           tmplen = tablesize + 20;
245           tmp = xtryrealloc (table, tmplen * sizeof *table);
246           if (!tmp)
247             {
248               err = gpg_error_from_syserror ();
249               goto leave;
250             }
251           table = tmp;
252           tablesize = tmplen;
253         }
254
255       ti = table + tableidx;
256
257       memset (&ti->flags, 0, sizeof ti->flags);
258       if (*p == '!')
259         {
260           ti->flags.disabled = 1;
261           p++;
262           while (spacep (p))
263             p++;
264         }
265
266       n = hexcolon2bin (p, ti->fpr, 20);
267       if (n < 0)
268         {
269           log_error (_("bad fingerprint in '%s', line %d\n"), fname, lnr);
270           err = gpg_error (GPG_ERR_BAD_DATA);
271           continue;
272         }
273       p += n;
274       for (; spacep (p); p++)
275         ;
276
277       /* Process the first flag which needs to be the first for
278          backward compatibility. */
279       if (!*p || *p == '*' )
280         {
281           ti->flags.for_smime = 1;
282           ti->flags.for_pgp = 1;
283         }
284       else if ( *p == 'P' || *p == 'p')
285         {
286           ti->flags.for_pgp = 1;
287         }
288       else if ( *p == 'S' || *p == 's')
289         {
290           ti->flags.for_smime = 1;
291         }
292       else
293         {
294           log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
295           err = gpg_error (GPG_ERR_BAD_DATA);
296           continue;
297         }
298       p++;
299       if ( *p && !spacep (p) )
300         {
301           log_error (_("invalid keyflag in '%s', line %d\n"), fname, lnr);
302           err = gpg_error (GPG_ERR_BAD_DATA);
303           continue;
304         }
305
306       /* Now check for more key-value pairs of the form NAME[=VALUE]. */
307       while (*p)
308         {
309           for (; spacep (p); p++)
310             ;
311           if (!*p)
312             break;
313           n = strcspn (p, "= \t");
314           if (p[n] == '=')
315             {
316               log_error ("assigning a value to a flag is not yet supported; "
317                          "in '%s', line %d\n", fname, lnr);
318               err = gpg_error (GPG_ERR_BAD_DATA);
319               p++;
320             }
321           else if (n == 5 && !memcmp (p, "relax", 5))
322             ti->flags.relax = 1;
323           else if (n == 2 && !memcmp (p, "cm", 2))
324             ti->flags.cm = 1;
325           else
326             log_error ("flag '%.*s' in '%s', line %d ignored\n",
327                        n, p, fname, lnr);
328           p += n;
329         }
330       tableidx++;
331     }
332   if ( !err && !es_feof (fp) )
333     {
334       err = gpg_error_from_syserror ();
335       log_error (_("error reading '%s', line %d: %s\n"),
336                  fname, lnr, gpg_strerror (err));
337     }
338
339  leave:
340   es_fclose (fp);
341   *addr_of_table = table;
342   *addr_of_tablesize = tablesize;
343   *addr_of_tableidx = tableidx;
344   return err;
345 }
346
347
348 /* Read the trust files and update the global table on success.  The
349    trusttable is assumed to be locked. */
350 static gpg_error_t
351 read_trustfiles (void)
352 {
353   gpg_error_t err;
354   trustitem_t *table, *ti;
355   int tableidx;
356   size_t tablesize;
357   char *fname;
358   int systrust = 0;
359   gpg_err_code_t ec;
360
361   tablesize = 20;
362   table = xtrycalloc (tablesize, sizeof *table);
363   if (!table)
364     return gpg_error_from_syserror ();
365   tableidx = 0;
366
367   if (opt.no_user_trustlist)
368     fname = NULL;
369   else
370     {
371       fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
372       if (!fname)
373         {
374           err = gpg_error_from_syserror ();
375           xfree (table);
376           return err;
377         }
378     }
379
380   if (!fname || (ec = gnupg_access (fname, F_OK)))
381     {
382       if (!fname)
383         ; /* --no-user-trustlist active.  */
384       else if ( ec == GPG_ERR_ENOENT )
385         ; /* Silently ignore a non-existing trustfile.  */
386       else
387         {
388           err = gpg_error (ec);
389           log_error (_("error opening '%s': %s\n"), fname, gpg_strerror (err));
390         }
391       xfree (fname);
392       fname = make_sys_trustlist_name ();
393       systrust = 1;
394     }
395   err = read_one_trustfile (fname, systrust, &table, &tablesize, &tableidx);
396   xfree (fname);
397
398   if (err)
399     {
400       xfree (table);
401       if (gpg_err_code (err) == GPG_ERR_ENOENT)
402         {
403           /* Take a missing trustlist as an empty one.  */
404           clear_trusttable ();
405           err = 0;
406         }
407       return err;
408     }
409
410   /* Fixme: we should drop duplicates and sort the table. */
411   ti = xtryrealloc (table, (tableidx?tableidx:1) * sizeof *table);
412   if (!ti)
413     {
414       err = gpg_error_from_syserror ();
415       xfree (table);
416       return err;
417     }
418
419   /* Replace the trusttable.  */
420   xfree (trusttable);
421   trusttable = ti;
422   trusttablesize = tableidx;
423   return 0;
424 }
425
426
427 /* Check whether the given fpr is in our trustdb.  We expect FPR to be
428    an all uppercase hexstring of 40 characters.  If ALREADY_LOCKED is
429    true the function assumes that the trusttable is already locked. */
430 static gpg_error_t
431 istrusted_internal (ctrl_t ctrl, const char *fpr, int *r_disabled,
432                     int already_locked)
433 {
434   gpg_error_t err = 0;
435   int locked = already_locked;
436   trustitem_t *ti;
437   size_t len;
438   unsigned char fprbin[20];
439
440   if (r_disabled)
441     *r_disabled = 0;
442
443   if ( hexcolon2bin (fpr, fprbin, 20) < 0 )
444     {
445       err = gpg_error (GPG_ERR_INV_VALUE);
446       goto leave;
447     }
448
449   if (!already_locked)
450     {
451       lock_trusttable ();
452       locked = 1;
453     }
454
455   if (!trusttable)
456     {
457       err = read_trustfiles ();
458       if (err)
459         {
460           log_error (_("error reading list of trusted root certificates\n"));
461           goto leave;
462         }
463     }
464
465   if (trusttable)
466     {
467       for (ti=trusttable, len = trusttablesize; len; ti++, len--)
468         if (!memcmp (ti->fpr, fprbin, 20))
469           {
470             if (ti->flags.disabled && r_disabled)
471               *r_disabled = 1;
472
473             /* Print status messages only if we have not been called
474                in a locked state.  */
475             if (already_locked)
476               ;
477             else if (ti->flags.relax)
478               {
479                 unlock_trusttable ();
480                 locked = 0;
481                 err = agent_write_status (ctrl, "TRUSTLISTFLAG", "relax", NULL);
482               }
483             else if (ti->flags.cm)
484               {
485                 unlock_trusttable ();
486                 locked = 0;
487                 err = agent_write_status (ctrl, "TRUSTLISTFLAG", "cm", NULL);
488               }
489
490             if (!err)
491               err = ti->flags.disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
492             goto leave;
493           }
494     }
495   err = gpg_error (GPG_ERR_NOT_TRUSTED);
496
497  leave:
498   if (locked && !already_locked)
499     unlock_trusttable ();
500   return err;
501 }
502
503
504 /* Check whether the given fpr is in our trustdb.  We expect FPR to be
505    an all uppercase hexstring of 40 characters.  */
506 gpg_error_t
507 agent_istrusted (ctrl_t ctrl, const char *fpr, int *r_disabled)
508 {
509   return istrusted_internal (ctrl, fpr, r_disabled, 0);
510 }
511
512
513 /* Write all trust entries to FP. */
514 gpg_error_t
515 agent_listtrusted (void *assuan_context)
516 {
517   trustitem_t *ti;
518   char key[51];
519   gpg_error_t err;
520   size_t len;
521
522   lock_trusttable ();
523   if (!trusttable)
524     {
525       err = read_trustfiles ();
526       if (err)
527         {
528           unlock_trusttable ();
529           log_error (_("error reading list of trusted root certificates\n"));
530           return err;
531         }
532     }
533
534   if (trusttable)
535     {
536       for (ti=trusttable, len = trusttablesize; len; ti++, len--)
537         {
538           if (ti->flags.disabled)
539             continue;
540           bin2hex (ti->fpr, 20, key);
541           key[40] = ' ';
542           key[41] = ((ti->flags.for_smime && ti->flags.for_pgp)? '*'
543                      : ti->flags.for_smime? 'S': ti->flags.for_pgp? 'P':' ');
544           key[42] = '\n';
545           assuan_send_data (assuan_context, key, 43);
546           assuan_send_data (assuan_context, NULL, 0); /* flush */
547         }
548     }
549
550   unlock_trusttable ();
551   return 0;
552 }
553
554
555 /* Create a copy of string with colons inserted after each two bytes.
556    Caller needs to release the string.  In case of a memory failure,
557    NULL is returned.  */
558 static char *
559 insert_colons (const char *string)
560 {
561   char *buffer, *p;
562   size_t n = strlen (string);
563   size_t nnew = n + (n+1)/2;
564
565   p = buffer = xtrymalloc ( nnew + 1 );
566   if (!buffer)
567     return NULL;
568   while (*string)
569     {
570       *p++ = *string++;
571       if (*string)
572         {
573           *p++ = *string++;
574           if (*string)
575             *p++ = ':';
576         }
577     }
578   *p = 0;
579   assert (strlen (buffer) <= nnew);
580
581   return buffer;
582 }
583
584
585 /* To pretty print DNs in the Pinentry, we replace slashes by
586    REPLSTRING.  The caller needs to free the returned string.  NULL is
587    returned on error with ERRNO set.  */
588 static char *
589 reformat_name (const char *name, const char *replstring)
590 {
591   const char *s;
592   char *newname;
593   char *d;
594   size_t count;
595   size_t replstringlen = strlen (replstring);
596
597   /* If the name does not start with a slash it is not a preformatted
598      DN and thus we don't bother to reformat it.  */
599   if (*name != '/')
600     return xtrystrdup (name);
601
602   /* Count the names.  Note that a slash contained in a DN part is
603      expected to be C style escaped and thus the slashes we see here
604      are the actual part delimiters.  */
605   for (s=name+1, count=0; *s; s++)
606     if (*s == '/')
607       count++;
608   newname = xtrymalloc (strlen (name) + count*replstringlen + 1);
609   if (!newname)
610     return NULL;
611   for (s=name+1, d=newname; *s; s++)
612     if (*s == '/')
613       d = stpcpy (d, replstring);
614     else
615       *d++ = *s;
616   *d = 0;
617   return newname;
618 }
619
620
621 /* Insert the given fpr into our trustdb.  We expect FPR to be an all
622    uppercase hexstring of 40 characters. FLAG is either 'P' or 'C'.
623    This function does first check whether that key has already been
624    put into the trustdb and returns success in this case.  Before a
625    FPR actually gets inserted, the user is asked by means of the
626    Pinentry whether this is actual what he wants to do.  */
627 gpg_error_t
628 agent_marktrusted (ctrl_t ctrl, const char *name, const char *fpr, int flag)
629 {
630   gpg_error_t err = 0;
631   gpg_err_code_t ec;
632   char *desc;
633   char *fname;
634   estream_t fp;
635   char *fprformatted;
636   char *nameformatted;
637   int is_disabled;
638   int yes_i_trust;
639
640   /* Check whether we are at all allowed to modify the trustlist.
641      This is useful so that the trustlist may be a symlink to a global
642      trustlist with only admin privileges to modify it.  Of course
643      this is not a secure way of denying access, but it avoids the
644      usual clicking on an Okay button most users are used to. */
645   fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
646   if (!fname)
647     return gpg_error_from_syserror ();
648
649   if ((ec = access (fname, W_OK)) && ec != GPG_ERR_ENOENT)
650     {
651       xfree (fname);
652       return gpg_error (GPG_ERR_EPERM);
653     }
654   xfree (fname);
655
656   if (!agent_istrusted (ctrl, fpr, &is_disabled))
657     {
658       return 0; /* We already got this fingerprint.  Silently return
659                    success. */
660     }
661
662   /* This feature must explicitly been enabled. */
663   if (!opt.allow_mark_trusted)
664     return gpg_error (GPG_ERR_NOT_SUPPORTED);
665
666   if (is_disabled)
667     {
668       /* There is an disabled entry in the trustlist.  Return an error
669          so that the user won't be asked again for that one.  Changing
670          this flag with the integrated marktrusted feature is and will
671          not be made possible.  */
672       return gpg_error (GPG_ERR_NOT_TRUSTED);
673     }
674
675
676   /* Insert a new one. */
677   nameformatted = reformat_name (name, "%0A   ");
678   if (!nameformatted)
679     return gpg_error_from_syserror ();
680
681   /* First a general question whether this is trusted.  */
682   desc = xtryasprintf (
683                 /* TRANSLATORS: This prompt is shown by the Pinentry
684                    and has one special property: A "%%0A" is used by
685                    Pinentry to insert a line break.  The double
686                    percent sign is actually needed because it is also
687                    a printf format string.  If you need to insert a
688                    plain % sign, you need to encode it as "%%25".  The
689                    "%s" gets replaced by the name as stored in the
690                    certificate. */
691                 L_("Do you ultimately trust%%0A"
692                    "  \"%s\"%%0A"
693                    "to correctly certify user certificates?"),
694                 nameformatted);
695   if (!desc)
696     {
697       xfree (nameformatted);
698       return out_of_core ();
699     }
700   err = agent_get_confirmation (ctrl, desc, L_("Yes"), L_("No"), 1);
701   xfree (desc);
702   if (!err)
703     yes_i_trust = 1;
704   else if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
705     yes_i_trust = 0;
706   else
707     {
708       xfree (nameformatted);
709       return err;
710     }
711
712
713   fprformatted = insert_colons (fpr);
714   if (!fprformatted)
715     {
716       xfree (nameformatted);
717       return out_of_core ();
718     }
719
720   /* If the user trusts this certificate he has to verify the
721      fingerprint of course.  */
722   if (yes_i_trust)
723     {
724       desc = xtryasprintf
725         (
726          /* TRANSLATORS: This prompt is shown by the Pinentry and has
727             one special property: A "%%0A" is used by Pinentry to
728             insert a line break.  The double percent sign is actually
729             needed because it is also a printf format string.  If you
730             need to insert a plain % sign, you need to encode it as
731             "%%25".  The second "%s" gets replaced by a hexdecimal
732             fingerprint string whereas the first one receives the name
733             as stored in the certificate. */
734          L_("Please verify that the certificate identified as:%%0A"
735             "  \"%s\"%%0A"
736             "has the fingerprint:%%0A"
737             "  %s"), nameformatted, fprformatted);
738       if (!desc)
739         {
740           xfree (fprformatted);
741           xfree (nameformatted);
742           return out_of_core ();
743         }
744
745       /* TRANSLATORS: "Correct" is the label of a button and intended
746          to be hit if the fingerprint matches the one of the CA.  The
747          other button is "the default "Cancel" of the Pinentry. */
748       err = agent_get_confirmation (ctrl, desc, L_("Correct"), L_("Wrong"), 1);
749       xfree (desc);
750       if (gpg_err_code (err) == GPG_ERR_NOT_CONFIRMED)
751         yes_i_trust = 0;
752       else if (err)
753         {
754           xfree (fprformatted);
755           xfree (nameformatted);
756           return err;
757         }
758     }
759
760
761   /* Now check again to avoid duplicates.  We take the lock to make
762      sure that nobody else plays with our file and force a reread.  */
763   lock_trusttable ();
764   clear_trusttable ();
765   if (!istrusted_internal (ctrl, fpr, &is_disabled, 1) || is_disabled)
766     {
767       unlock_trusttable ();
768       xfree (fprformatted);
769       xfree (nameformatted);
770       return is_disabled? gpg_error (GPG_ERR_NOT_TRUSTED) : 0;
771     }
772
773   fname = make_filename_try (gnupg_homedir (), "trustlist.txt", NULL);
774   if (!fname)
775     {
776       err = gpg_error_from_syserror ();
777       unlock_trusttable ();
778       xfree (fprformatted);
779       xfree (nameformatted);
780       return err;
781     }
782   if ((ec = access (fname, F_OK)) && ec == GPG_ERR_ENOENT)
783     {
784       fp = es_fopen (fname, "wx,mode=-rw-r");
785       if (!fp)
786         {
787           err = gpg_error (ec);
788           log_error ("can't create '%s': %s\n", fname, gpg_strerror (err));
789           xfree (fname);
790           unlock_trusttable ();
791           xfree (fprformatted);
792           xfree (nameformatted);
793           return err;
794         }
795       es_fputs (headerblurb, fp);
796       es_fclose (fp);
797     }
798   fp = es_fopen (fname, "a+,mode=-rw-r");
799   if (!fp)
800     {
801       err = gpg_error_from_syserror ();
802       log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
803       xfree (fname);
804       unlock_trusttable ();
805       xfree (fprformatted);
806       xfree (nameformatted);
807       return err;
808     }
809
810   /* Append the key. */
811   es_fputs ("\n# ", fp);
812   xfree (nameformatted);
813   nameformatted = reformat_name (name, "\n# ");
814   if (!nameformatted || strchr (name, '\n'))
815     {
816       /* Note that there should never be a LF in NAME but we better
817          play safe and print a sanitized version in this case.  */
818       es_write_sanitized (fp, name, strlen (name), NULL, NULL);
819     }
820   else
821     es_fputs (nameformatted, fp);
822   es_fprintf (fp, "\n%s%s %c%s\n", yes_i_trust?"":"!", fprformatted, flag,
823               flag == 'S'? " relax":"");
824   if (es_ferror (fp))
825     err = gpg_error_from_syserror ();
826
827   if (es_fclose (fp))
828     err = gpg_error_from_syserror ();
829
830   clear_trusttable ();
831   xfree (fname);
832   unlock_trusttable ();
833   xfree (fprformatted);
834   xfree (nameformatted);
835   if (!err)
836     bump_key_eventcounter ();
837   return err;
838 }
839
840
841 /* This function may be called to force reloading of the
842    trustlist.  */
843 void
844 agent_reload_trustlist (void)
845 {
846   /* All we need to do is to delete the trusttable.  At the next
847      access it will get re-read. */
848   lock_trusttable ();
849   clear_trusttable ();
850   unlock_trusttable ();
851   bump_key_eventcounter ();
852 }