chiark / gitweb /
dirmngr: Fix error handling.
[gnupg2.git] / g10 / tofu.c
1 /* tofu.c - TOFU trust model.
2  * Copyright (C) 2015, 2016 g10 Code GmbH
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <https://www.gnu.org/licenses/>.
18  */
19
20 /* TODO:
21
22    - Format the fingerprints nicely when printing (similar to gpg
23      --list-keys)
24  */
25
26 #include <config.h>
27 #include <stdio.h>
28 #include <sys/stat.h>
29 #include <stdarg.h>
30 #include <sqlite3.h>
31 #include <time.h>
32
33 #include "gpg.h"
34 #include "types.h"
35 #include "logging.h"
36 #include "stringhelp.h"
37 #include "options.h"
38 #include "mbox-util.h"
39 #include "i18n.h"
40 #include "ttyio.h"
41 #include "trustdb.h"
42 #include "mkdir_p.h"
43 #include "gpgsql.h"
44 #include "status.h"
45 #include "sqrtu32.h"
46
47 #include "tofu.h"
48
49
50 #define CONTROL_L ('L' - 'A' + 1)
51
52 /* Number of days with signed / ecnrypted messages required to
53  * indicate that enough history is available for basic trust.  */
54 #define BASIC_TRUST_THRESHOLD  4
55 /* Number of days with signed / encrypted messages required to
56  * indicate that a lot of history is available.  */
57 #define FULL_TRUST_THRESHOLD  21
58
59
60 /* A struct with data pertaining to the tofu DB.  There is one such
61    struct per session and it is cached in session's ctrl structure.
62    To initialize this or get the current singleton, call opendbs().
63    There is no need to explicitly release it; cleanup is done when the
64    CTRL object is released.  */
65 struct tofu_dbs_s
66 {
67   sqlite3 *db;
68   char *want_lock_file;
69   time_t want_lock_file_ctime;
70
71   struct
72   {
73     sqlite3_stmt *savepoint_batch;
74     sqlite3_stmt *savepoint_batch_commit;
75
76     sqlite3_stmt *record_binding_get_old_policy;
77     sqlite3_stmt *record_binding_update;
78     sqlite3_stmt *get_policy_select_policy_and_conflict;
79     sqlite3_stmt *get_trust_bindings_with_this_email;
80     sqlite3_stmt *get_trust_gather_other_user_ids;
81     sqlite3_stmt *get_trust_gather_signature_stats;
82     sqlite3_stmt *get_trust_gather_encryption_stats;
83     sqlite3_stmt *register_already_seen;
84     sqlite3_stmt *register_signature;
85     sqlite3_stmt *register_encryption;
86   } s;
87
88   int in_batch_transaction;
89   int in_transaction;
90   time_t batch_update_started;
91 };
92
93
94 #define STRINGIFY(s) STRINGIFY2(s)
95 #define STRINGIFY2(s) #s
96
97 /* The grouping parameters when collecting signature statistics.  */
98
99 /* If a message is signed a couple of hours in the future, just assume
100    some clock skew.  */
101 #define TIME_AGO_FUTURE_IGNORE (2 * 60 * 60)
102 /* Days.  */
103 #define TIME_AGO_UNIT_SMALL (24 * 60 * 60)
104 #define TIME_AGO_SMALL_THRESHOLD (7 * TIME_AGO_UNIT_SMALL)
105 /* Months.  */
106 #define TIME_AGO_UNIT_MEDIUM (30 * 24 * 60 * 60)
107 #define TIME_AGO_MEDIUM_THRESHOLD (2 * TIME_AGO_UNIT_MEDIUM)
108 /* Years.  */
109 #define TIME_AGO_UNIT_LARGE (365 * 24 * 60 * 60)
110 #define TIME_AGO_LARGE_THRESHOLD (2 * TIME_AGO_UNIT_LARGE)
111
112 /* Local prototypes.  */
113 static gpg_error_t end_transaction (ctrl_t ctrl, int only_batch);
114 static char *email_from_user_id (const char *user_id);
115 static int show_statistics (tofu_dbs_t dbs,
116                             const char *fingerprint, const char *email,
117                             enum tofu_policy policy,
118                             estream_t outfp, int only_status_fd, time_t now);
119 \f
120 const char *
121 tofu_policy_str (enum tofu_policy policy)
122 {
123   switch (policy)
124     {
125     case TOFU_POLICY_NONE: return "none";
126     case TOFU_POLICY_AUTO: return "auto";
127     case TOFU_POLICY_GOOD: return "good";
128     case TOFU_POLICY_UNKNOWN: return "unknown";
129     case TOFU_POLICY_BAD: return "bad";
130     case TOFU_POLICY_ASK: return "ask";
131     default: return "???";
132     }
133 }
134
135 /* Convert a binding policy (e.g., TOFU_POLICY_BAD) to a trust level
136    (e.g., TRUST_BAD) in light of the current configuration.  */
137 int
138 tofu_policy_to_trust_level (enum tofu_policy policy)
139 {
140   if (policy == TOFU_POLICY_AUTO)
141     /* If POLICY is AUTO, fallback to OPT.TOFU_DEFAULT_POLICY.  */
142     policy = opt.tofu_default_policy;
143
144   switch (policy)
145     {
146     case TOFU_POLICY_AUTO:
147       /* If POLICY and OPT.TOFU_DEFAULT_POLICY are both AUTO, default
148          to marginal trust.  */
149       return TRUST_MARGINAL;
150     case TOFU_POLICY_GOOD:
151       return TRUST_FULLY;
152     case TOFU_POLICY_UNKNOWN:
153       return TRUST_UNKNOWN;
154     case TOFU_POLICY_BAD:
155       return TRUST_NEVER;
156     case TOFU_POLICY_ASK:
157       return TRUST_UNKNOWN;
158     default:
159       log_bug ("Bad value for trust policy: %d\n",
160                opt.tofu_default_policy);
161       return 0;
162     }
163 }
164
165
166 \f
167 /* Start a transaction on DB.  If ONLY_BATCH is set, then this will
168    start a batch transaction if we haven't started a batch transaction
169    and one has been requested.  */
170 static gpg_error_t
171 begin_transaction (ctrl_t ctrl, int only_batch)
172 {
173   tofu_dbs_t dbs = ctrl->tofu.dbs;
174   int rc;
175   char *err = NULL;
176
177   log_assert (dbs);
178
179   /* If we've been in batch update mode for a while (on average, more
180    * than 500 ms), to prevent starving other gpg processes, we drop
181    * and retake the batch lock.
182    *
183    * Note: gnupg_get_time has a one second resolution, if we wanted a
184    * higher resolution, we could use npth_clock_gettime.  */
185   if (/* No real transactions.  */
186       dbs->in_transaction == 0
187       /* There is an open batch transaction.  */
188       && dbs->in_batch_transaction
189       /* And some time has gone by since it was started.  */
190       && dbs->batch_update_started != gnupg_get_time ())
191     {
192       struct stat statbuf;
193
194       /* If we are in a batch update, then batch updates better have
195          been enabled.  */
196       log_assert (ctrl->tofu.batch_updated_wanted);
197
198       /* Check if another process wants to run.  (We just ignore any
199        * stat failure.  A waiter might have to wait a bit longer, but
200        * otherwise there should be no impact.)  */
201       if (stat (dbs->want_lock_file, &statbuf) == 0
202           && statbuf.st_ctime != dbs->want_lock_file_ctime)
203         {
204           end_transaction (ctrl, 2);
205
206           /* Yield to allow another process a chance to run.  Note:
207            * testing suggests that anything less than a 100ms tends to
208            * not result in the other process getting the lock.  */
209           gnupg_usleep (100000);
210         }
211       else
212         dbs->batch_update_started = gnupg_get_time ();
213     }
214
215   if (/* We don't have an open batch transaction.  */
216       !dbs->in_batch_transaction
217       && (/* Batch mode is enabled or we are starting a new transaction.  */
218           ctrl->tofu.batch_updated_wanted || dbs->in_transaction == 0))
219     {
220       struct stat statbuf;
221
222       /* We are in batch mode, but we don't have an open batch
223        * transaction.  Since the batch save point must be the outer
224        * save point, it must be taken before the inner save point.  */
225       log_assert (dbs->in_transaction == 0);
226
227       rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch,
228                           NULL, NULL, &err,
229                           "begin immediate transaction;", GPGSQL_ARG_END);
230       if (rc)
231         {
232           log_error (_("error beginning transaction on TOFU database: %s\n"),
233                      err);
234           sqlite3_free (err);
235           return gpg_error (GPG_ERR_GENERAL);
236         }
237
238       dbs->in_batch_transaction = 1;
239       dbs->batch_update_started = gnupg_get_time ();
240
241       if (stat (dbs->want_lock_file, &statbuf) == 0)
242         dbs->want_lock_file_ctime = statbuf.st_ctime;
243     }
244
245   if (only_batch)
246     return 0;
247
248   log_assert (dbs->in_transaction >= 0);
249   dbs->in_transaction ++;
250
251   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
252                            "savepoint inner%d;",
253                            dbs->in_transaction);
254   if (rc)
255     {
256       log_error (_("error beginning transaction on TOFU database: %s\n"),
257                  err);
258       sqlite3_free (err);
259       return gpg_error (GPG_ERR_GENERAL);
260     }
261
262   return 0;
263 }
264
265
266 /* Commit a transaction.  If ONLY_BATCH is 1, then this only ends the
267  * batch transaction if we have left batch mode.  If ONLY_BATCH is 2,
268  * this commits any open batch transaction even if we are still in
269  * batch mode.  */
270 static gpg_error_t
271 end_transaction (ctrl_t ctrl, int only_batch)
272 {
273   tofu_dbs_t dbs = ctrl->tofu.dbs;
274   int rc;
275   char *err = NULL;
276
277   if (only_batch || (! only_batch && dbs->in_transaction == 1))
278     {
279       if (!dbs)
280         return 0;  /* Shortcut to allow for easier cleanup code.  */
281
282       /* If we are releasing the batch transaction, then we better not
283          be in a normal transaction.  */
284       if (only_batch)
285         log_assert (dbs->in_transaction == 0);
286
287       if (/* Batch mode disabled?  */
288           (!ctrl->tofu.batch_updated_wanted || only_batch == 2)
289           /* But, we still have an open batch transaction?  */
290           && dbs->in_batch_transaction)
291         {
292           /* The batch transaction is still in open, but we've left
293            * batch mode.  */
294           dbs->in_batch_transaction = 0;
295           dbs->in_transaction = 0;
296
297           rc = gpgsql_stepx (dbs->db, &dbs->s.savepoint_batch_commit,
298                              NULL, NULL, &err,
299                              "commit transaction;", GPGSQL_ARG_END);
300           if (rc)
301             {
302               log_error (_("error committing transaction on TOFU database: %s\n"),
303                          err);
304               sqlite3_free (err);
305               return gpg_error (GPG_ERR_GENERAL);
306             }
307
308           return 0;
309         }
310
311       if (only_batch)
312         return 0;
313     }
314
315   log_assert (dbs);
316   log_assert (dbs->in_transaction > 0);
317
318   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
319                            "release inner%d;", dbs->in_transaction);
320
321   dbs->in_transaction --;
322
323   if (rc)
324     {
325       log_error (_("error committing transaction on TOFU database: %s\n"),
326                  err);
327       sqlite3_free (err);
328       return gpg_error (GPG_ERR_GENERAL);
329     }
330
331   return 0;
332 }
333
334
335 static gpg_error_t
336 rollback_transaction (ctrl_t ctrl)
337 {
338   tofu_dbs_t dbs = ctrl->tofu.dbs;
339   int rc;
340   char *err = NULL;
341
342   log_assert (dbs);
343   log_assert (dbs->in_transaction > 0);
344
345   /* Be careful to not undo any progress made by closed transactions in
346      batch mode.  */
347   rc = gpgsql_exec_printf (dbs->db, NULL, NULL, &err,
348                            "rollback to inner%d;",
349                            dbs->in_transaction);
350
351   dbs->in_transaction --;
352
353   if (rc)
354     {
355       log_error (_("error rolling back transaction on TOFU database: %s\n"),
356                  err);
357       sqlite3_free (err);
358       return gpg_error (GPG_ERR_GENERAL);
359     }
360
361   return 0;
362 }
363
364 void
365 tofu_begin_batch_update (ctrl_t ctrl)
366 {
367   ctrl->tofu.batch_updated_wanted ++;
368 }
369
370 void
371 tofu_end_batch_update (ctrl_t ctrl)
372 {
373   log_assert (ctrl->tofu.batch_updated_wanted > 0);
374   ctrl->tofu.batch_updated_wanted --;
375   end_transaction (ctrl, 1);
376 }
377
378 /* Suspend any extant batch transaction (it is safe to call this even
379    no batch transaction has been started).  Note: you cannot suspend a
380    batch transaction if you are in a normal transaction.  The batch
381    transaction can be resumed explicitly by calling
382    tofu_resume_batch_transaction or implicitly by starting a normal
383    transaction.  */
384 static void
385 tofu_suspend_batch_transaction (ctrl_t ctrl)
386 {
387   end_transaction (ctrl, 2);
388 }
389
390 /* Resume a batch transaction if there is no extant batch transaction
391    and one has been requested using tofu_begin_batch_transaction.  */
392 static void
393 tofu_resume_batch_transaction (ctrl_t ctrl)
394 {
395   begin_transaction (ctrl, 1);
396 }
397
398
399 \f
400 /* Wrapper around strtol which prints a warning in case of a
401  * conversion error.  On success the converted value is stored at
402  * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
403  * and an error code is returned.  */
404 static gpg_error_t
405 string_to_long (long *r_value, const char *string, long fallback, int line)
406 {
407   gpg_error_t err;
408   char *tail = NULL;
409
410   gpg_err_set_errno (0);
411   *r_value = strtol (string, &tail, 0);
412   if (errno || !(!strcmp (tail, ".0") || !*tail))
413     {
414       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
415       log_debug ("%s:%d: strtol failed for TOFU DB data; returned string"
416                  " (string='%.10s%s'; tail='%.10s%s'): %s\n",
417                  __FILE__, line,
418                  string, string && strlen(string) > 10 ? "..." : "",
419                  tail, tail && strlen(tail) > 10 ? "..." : "",
420                  gpg_strerror (err));
421       *r_value = fallback;
422     }
423   else
424     err = 0;
425
426   return err;
427 }
428
429
430 /* Wrapper around strtoul which prints a warning in case of a
431  * conversion error.  On success the converted value is stored at
432  * R_VALUE and 0 is returned; on error FALLBACK is stored at R_VALUE
433  * and an error code is returned.  */
434 static gpg_error_t
435 string_to_ulong (unsigned long *r_value, const char *string,
436                  unsigned long fallback, int line)
437 {
438   gpg_error_t err;
439   char *tail = NULL;
440
441   gpg_err_set_errno (0);
442   *r_value = strtoul (string, &tail, 0);
443   if (errno || !(!strcmp (tail, ".0") || !*tail))
444     {
445       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
446       log_debug ("%s:%d: strtoul failed for TOFU DB data; returned string"
447                  " (string='%.10s%s'; tail='%.10s%s'): %s\n",
448                  __FILE__, line,
449                  string, string && strlen(string) > 10 ? "..." : "",
450                  tail, tail && strlen(tail) > 10 ? "..." : "",
451                  gpg_strerror (err));
452       *r_value = fallback;
453     }
454   else
455     err = 0;
456
457   return err;
458 }
459
460
461
462 /* Collect results of a select count (*) ...; style query.  Aborts if
463    the argument is not a valid integer (or real of the form X.0).  */
464 static int
465 get_single_unsigned_long_cb (void *cookie, int argc, char **argv,
466                              char **azColName)
467 {
468   unsigned long int *count = cookie;
469
470   (void) azColName;
471
472   log_assert (argc == 1);
473
474   if (string_to_ulong (count, argv[0], 0, __LINE__))
475     return 1; /* Abort.  */
476   return 0;
477 }
478
479 static int
480 get_single_unsigned_long_cb2 (void *cookie, int argc, char **argv,
481                              char **azColName, sqlite3_stmt *stmt)
482 {
483   (void) stmt;
484   return get_single_unsigned_long_cb (cookie, argc, argv, azColName);
485 }
486
487 /* We expect a single integer column whose name is "version".  COOKIE
488    must point to an int.  This function always aborts.  On error or a
489    if the version is bad, sets *VERSION to -1.  */
490 static int
491 version_check_cb (void *cookie, int argc, char **argv, char **azColName)
492 {
493   int *version = cookie;
494
495   if (argc != 1 || strcmp (azColName[0], "version") != 0)
496     {
497       *version = -1;
498       return 1;
499     }
500
501   if (strcmp (argv[0], "1") == 0)
502     *version = 1;
503   else
504     {
505       log_error (_("unsupported TOFU database version: %s\n"), argv[0]);
506       *version = -1;
507     }
508
509   /* Don't run again.  */
510   return 1;
511 }
512
513 static int
514 check_utks (sqlite3 *db)
515 {
516   int rc;
517   char *err = NULL;
518   struct key_item *utks;
519   struct key_item *ki;
520   int utk_count;
521   char *utks_string = NULL;
522   char keyid_str[16+1];
523   long utks_unchanged = 0;
524
525   /* An early version of the v1 format did not include the list of
526    * known ultimately trusted keys.
527    *
528    * This list is used to detect when the set of ultimately trusted
529    * keys changes.  We need to detect this to invalidate the effective
530    * policy, which can change if an ultimately trusted key is added or
531    * removed.  */
532   rc = sqlite3_exec (db,
533                      "create table if not exists ultimately_trusted_keys"
534                      " (keyid);\n",
535                      NULL, NULL, &err);
536   if (rc)
537     {
538       log_error (_("error creating 'ultimately_trusted_keys' TOFU table: %s\n"),
539                  err);
540       sqlite3_free (err);
541       goto out;
542     }
543
544
545   utks = tdb_utks ();
546   for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
547     ;
548
549   if (utk_count)
550     {
551       /* Build a list of keyids of the form "XXX","YYY","ZZZ".  */
552       int len = (1 + 16 + 1 + 1) * utk_count;
553       int o = 0;
554
555       utks_string = xmalloc (len);
556       *utks_string = 0;
557       for (ki = utks, utk_count = 0; ki; ki = ki->next, utk_count ++)
558         {
559           utks_string[o ++] = '\'';
560           format_keyid (ki->kid, KF_LONG,
561                         keyid_str, sizeof (keyid_str));
562           memcpy (&utks_string[o], keyid_str, 16);
563           o += 16;
564           utks_string[o ++] = '\'';
565           utks_string[o ++] = ',';
566         }
567       utks_string[o - 1] = 0;
568       log_assert (o == len);
569     }
570
571   rc = gpgsql_exec_printf
572     (db, get_single_unsigned_long_cb, &utks_unchanged, &err,
573      "select"
574      /* Removed UTKs?  (Known UTKs in current UTKs.)  */
575      "  ((select count(*) from ultimately_trusted_keys"
576      "     where (keyid in (%s))) == %d)"
577      " and"
578      /* New UTKs?  */
579      "  ((select count(*) from ultimately_trusted_keys"
580      "     where keyid not in (%s)) == 0);",
581      utks_string ? utks_string : "",
582      utk_count,
583      utks_string ? utks_string : "");
584   xfree (utks_string);
585   if (rc)
586     {
587       log_error (_("TOFU DB error"));
588       print_further_info ("checking if ultimately trusted keys changed: %s",
589                          err);
590       sqlite3_free (err);
591       goto out;
592     }
593
594   if (utks_unchanged)
595     goto out;
596
597   if (DBG_TRUST)
598     log_debug ("TOFU: ultimately trusted keys changed.\n");
599
600   /* Given that the set of ultimately trusted keys
601    * changed, clear any cached policies.  */
602   rc = gpgsql_exec_printf
603     (db, NULL, NULL, &err,
604      "update bindings set effective_policy = %d;",
605      TOFU_POLICY_NONE);
606   if (rc)
607     {
608       log_error (_("TOFU DB error"));
609       print_further_info ("clearing cached policies: %s", err);
610       sqlite3_free (err);
611       goto out;
612     }
613
614   /* Now, update the UTK table.  */
615   rc = sqlite3_exec (db,
616                      "drop table ultimately_trusted_keys;",
617                      NULL, NULL, &err);
618   if (rc)
619     {
620       log_error (_("TOFU DB error"));
621       print_further_info ("dropping ultimately_trusted_keys: %s", err);
622       sqlite3_free (err);
623       goto out;
624     }
625
626   rc = sqlite3_exec (db,
627                      "create table if not exists"
628                      " ultimately_trusted_keys (keyid);\n",
629                      NULL, NULL, &err);
630   if (rc)
631     {
632       log_error (_("TOFU DB error"));
633       print_further_info ("creating ultimately_trusted_keys: %s", err);
634       sqlite3_free (err);
635       goto out;
636     }
637
638   for (ki = utks; ki; ki = ki->next)
639     {
640       format_keyid (ki->kid, KF_LONG,
641                     keyid_str, sizeof (keyid_str));
642       rc = gpgsql_exec_printf
643         (db, NULL, NULL, &err,
644          "insert into ultimately_trusted_keys values ('%s');",
645          keyid_str);
646       if (rc)
647         {
648           log_error (_("TOFU DB error"));
649           print_further_info ("updating ultimately_trusted_keys: %s",
650                               err);
651           sqlite3_free (err);
652           goto out;
653         }
654     }
655
656  out:
657   return rc;
658 }
659
660 /* If the DB is new, initialize it.  Otherwise, check the DB's
661    version.
662
663    Return 0 if the database is okay and 1 otherwise.  */
664 static int
665 initdb (sqlite3 *db)
666 {
667   char *err = NULL;
668   int rc;
669   unsigned long int count;
670   int version = -1;
671
672   rc = sqlite3_exec (db, "begin transaction;", NULL, NULL, &err);
673   if (rc)
674     {
675       log_error (_("error beginning transaction on TOFU database: %s\n"),
676                  err);
677       sqlite3_free (err);
678       return 1;
679     }
680
681   /* If the DB has no tables, then assume this is a new DB that needs
682      to be initialized.  */
683   rc = sqlite3_exec (db,
684                      "select count(*) from sqlite_master where type='table';",
685                      get_single_unsigned_long_cb, &count, &err);
686   if (rc)
687     {
688       log_error (_("error reading TOFU database: %s\n"), err);
689       print_further_info ("query available tables");
690       sqlite3_free (err);
691       goto out;
692     }
693   else if (count != 0)
694     /* Assume that the DB is already initialized.  Make sure the
695        version is okay.  */
696     {
697       rc = sqlite3_exec (db, "select version from version;", version_check_cb,
698                          &version, &err);
699       if (rc == SQLITE_ABORT && version == 1)
700         /* Happy, happy, joy, joy.  */
701         {
702           sqlite3_free (err);
703           rc = 0;
704           goto out;
705         }
706       else if (rc == SQLITE_ABORT && version == -1)
707         /* Unsupported version.  */
708         {
709           /* An error message was already displayed.  */
710           sqlite3_free (err);
711           goto out;
712         }
713       else if (rc)
714         /* Some error.  */
715         {
716           log_error (_("error determining TOFU database's version: %s\n"), err);
717           sqlite3_free (err);
718           goto out;
719         }
720       else
721         {
722           /* Unexpected success.  This can only happen if there are no
723              rows.  (select returned 0, but expected ABORT.)  */
724           log_error (_("error determining TOFU database's version: %s\n"),
725                      gpg_strerror (GPG_ERR_NO_DATA));
726           rc = 1;
727           goto out;
728         }
729     }
730
731   /* Create the version table.  */
732   rc = sqlite3_exec (db,
733                      "create table version (version INTEGER);",
734                      NULL, NULL, &err);
735   if (rc)
736     {
737       log_error (_("error initializing TOFU database: %s\n"), err);
738       print_further_info ("create version");
739       sqlite3_free (err);
740       goto out;
741     }
742
743   /* Initialize the version table, which contains a single integer
744      value.  */
745   rc = sqlite3_exec (db,
746                      "insert into version values (1);",
747                      NULL, NULL, &err);
748   if (rc)
749     {
750       log_error (_("error initializing TOFU database: %s\n"), err);
751       print_further_info ("insert version");
752       sqlite3_free (err);
753       goto out;
754     }
755
756   /* The list of <fingerprint, email> bindings and auxiliary data.
757    *
758    *  OID is a unique ID identifying this binding (and used by the
759    *    signatures table, see below).  Note: OIDs will never be
760    *    reused.
761    *
762    *  FINGERPRINT: The key's fingerprint.
763    *
764    *  EMAIL: The normalized email address.
765    *
766    *  USER_ID: The unmodified user id from which EMAIL was extracted.
767    *
768    *  TIME: The time this binding was first observed.
769    *
770    *  POLICY: The trust policy (TOFU_POLICY_BAD, etc. as an integer).
771    *
772    *  CONFLICT is either NULL or a fingerprint.  Assume that we have
773    *    a binding <0xdeadbeef, foo@example.com> and then we observe
774    *    <0xbaddecaf, foo@example.com>.  There two bindings conflict
775    *    (they have the same email address).  When we observe the
776    *    latter binding, we warn the user about the conflict and ask
777    *    for a policy decision about the new binding.  We also change
778    *    the old binding's policy to ask if it was auto.  So that we
779    *     know why this occurred, we also set conflict to 0xbaddecaf.
780    */
781   rc = gpgsql_exec_printf
782       (db, NULL, NULL, &err,
783        "create table bindings\n"
784        " (oid INTEGER PRIMARY KEY AUTOINCREMENT,\n"
785        "  fingerprint TEXT, email TEXT, user_id TEXT, time INTEGER,\n"
786        "  policy INTEGER CHECK (policy in (%d, %d, %d, %d, %d)),\n"
787        "  conflict STRING,\n"
788        "  unique (fingerprint, email));\n"
789        "create index bindings_fingerprint_email\n"
790        " on bindings (fingerprint, email);\n"
791        "create index bindings_email on bindings (email);\n",
792        TOFU_POLICY_AUTO, TOFU_POLICY_GOOD, TOFU_POLICY_UNKNOWN,
793        TOFU_POLICY_BAD, TOFU_POLICY_ASK);
794   if (rc)
795     {
796       log_error (_("error initializing TOFU database: %s\n"), err);
797       print_further_info ("create bindings");
798       sqlite3_free (err);
799       goto out;
800     }
801
802   /* The signatures that we have observed.
803    *
804    * BINDING refers to a record in the bindings table, which
805    * describes the binding (i.e., this is a foreign key that
806    * references bindings.oid).
807    *
808    * SIG_DIGEST is the digest stored in the signature.
809    *
810    * SIG_TIME is the timestamp stored in the signature.
811    *
812    * ORIGIN is a free-form string that describes who fed this
813    * signature to GnuPG (e.g., email:claws).
814    *
815    * TIME is the time this signature was registered.  */
816   rc = sqlite3_exec (db,
817                          "create table signatures "
818                          " (binding INTEGER NOT NULL, sig_digest TEXT,"
819                          "  origin TEXT, sig_time INTEGER, time INTEGER,"
820                          "  primary key (binding, sig_digest, origin));",
821                          NULL, NULL, &err);
822   if (rc)
823     {
824       log_error (_("error initializing TOFU database: %s\n"), err);
825       print_further_info ("create signatures");
826       sqlite3_free (err);
827       goto out;
828     }
829
830  out:
831   if (! rc)
832     {
833       /* Early version of the v1 format did not include the encryption
834          table.  Add it.  */
835       rc = sqlite3_exec (db,
836                          "create table if not exists encryptions"
837                          " (binding INTEGER NOT NULL,"
838                          "  time INTEGER);"
839                          "create index if not exists encryptions_binding"
840                          " on encryptions (binding);\n",
841                          NULL, NULL, &err);
842       if (rc)
843         {
844           log_error (_("error creating 'encryptions' TOFU table: %s\n"),
845                      err);
846           sqlite3_free (err);
847         }
848     }
849   if (! rc)
850     {
851       /* The effective policy for a binding.  If a key is ultimately
852        * trusted, then the effective policy of all of its bindings is
853        * good.  Likewise if a key is signed by an ultimately trusted
854        * key, etc.  If the effective policy is NONE, then we need to
855        * recompute the effective policy.  Otherwise, the effective
856        * policy is considered to be up to date, i.e., effective_policy
857        * is a cache of the computed policy.  */
858       rc = gpgsql_exec_printf
859         (db, NULL, NULL, &err,
860          "alter table bindings"
861          " add column effective_policy INTEGER"
862          " DEFAULT %d"
863          " CHECK (effective_policy in (%d, %d, %d, %d, %d, %d));",
864          TOFU_POLICY_NONE,
865          TOFU_POLICY_NONE, TOFU_POLICY_AUTO, TOFU_POLICY_GOOD,
866          TOFU_POLICY_UNKNOWN, TOFU_POLICY_BAD, TOFU_POLICY_ASK);
867       if (rc)
868         {
869           if (rc == SQLITE_ERROR)
870             /* Almost certainly "duplicate column name", which we can
871              * safely ignore.  */
872             rc = 0;
873           else
874             log_error (_("adding column effective_policy to bindings DB: %s\n"),
875                        err);
876           sqlite3_free (err);
877         }
878     }
879
880   if (! rc)
881     rc = check_utks (db);
882
883   if (rc)
884     {
885       rc = sqlite3_exec (db, "rollback;", NULL, NULL, &err);
886       if (rc)
887         {
888           log_error (_("error rolling back transaction on TOFU database: %s\n"),
889                      err);
890           sqlite3_free (err);
891         }
892       return 1;
893     }
894   else
895     {
896       rc = sqlite3_exec (db, "end transaction;", NULL, NULL, &err);
897       if (rc)
898         {
899           log_error (_("error committing transaction on TOFU database: %s\n"),
900                      err);
901           sqlite3_free (err);
902           return 1;
903         }
904       return 0;
905     }
906 }
907
908 static int
909 busy_handler (void *cookie, int call_count)
910 {
911   ctrl_t ctrl = cookie;
912   tofu_dbs_t dbs = ctrl->tofu.dbs;
913
914   (void) call_count;
915
916   /* Update the want-lock-file time stamp (specifically, the ctime) so
917    * that the current owner knows that we (well, someone) want the
918    * lock.  */
919   if (dbs)
920     {
921       /* Note: we don't fail if we can't create the lock file: this
922        * process will have to wait a bit longer, but otherwise nothing
923        * horrible should happen.  */
924
925       estream_t fp;
926
927       fp = es_fopen (dbs->want_lock_file, "w");
928       if (! fp)
929         log_debug ("TOFU: Error opening '%s': %s\n",
930                    dbs->want_lock_file, strerror (errno));
931       else
932         es_fclose (fp);
933     }
934
935   /* Call again.  */
936   return 1;
937 }
938
939 /* Create a new DB handle.  Returns NULL on error.  */
940 /* FIXME: Change to return an error code for better reporting by the
941    caller.  */
942 static tofu_dbs_t
943 opendbs (ctrl_t ctrl)
944 {
945   char *filename;
946   sqlite3 *db;
947   int rc;
948
949   if (!ctrl->tofu.dbs)
950     {
951       filename = make_filename (gnupg_homedir (), "tofu.db", NULL);
952
953       rc = sqlite3_open (filename, &db);
954       if (rc)
955         {
956           log_error (_("error opening TOFU database '%s': %s\n"),
957                      filename, sqlite3_errmsg (db));
958           /* Even if an error occurs, DB is guaranteed to be valid.  */
959           sqlite3_close (db);
960           db = NULL;
961         }
962
963       /* If a DB is locked wait up to 5 seconds for the lock to be cleared
964          before failing.  */
965       if (db)
966         {
967           sqlite3_busy_timeout (db, 5 * 1000);
968           sqlite3_busy_handler (db, busy_handler, ctrl);
969         }
970
971       if (db && initdb (db))
972         {
973           sqlite3_close (db);
974           db = NULL;
975         }
976
977       if (db)
978         {
979           ctrl->tofu.dbs = xmalloc_clear (sizeof *ctrl->tofu.dbs);
980           ctrl->tofu.dbs->db = db;
981           ctrl->tofu.dbs->want_lock_file = xasprintf ("%s-want-lock", filename);
982         }
983
984       xfree (filename);
985     }
986   else
987     log_assert (ctrl->tofu.dbs->db);
988
989   return ctrl->tofu.dbs;
990 }
991
992
993 /* Release all of the resources associated with the DB handle.  */
994 void
995 tofu_closedbs (ctrl_t ctrl)
996 {
997   tofu_dbs_t dbs;
998   sqlite3_stmt **statements;
999
1000   dbs = ctrl->tofu.dbs;
1001   if (!dbs)
1002     return;  /* Not initialized.  */
1003
1004   log_assert (dbs->in_transaction == 0);
1005
1006   end_transaction (ctrl, 2);
1007
1008   /* Arghh, that is a surprising use of the struct.  */
1009   for (statements = (void *) &dbs->s;
1010        (void *) statements < (void *) &(&dbs->s)[1];
1011        statements ++)
1012     sqlite3_finalize (*statements);
1013
1014   sqlite3_close (dbs->db);
1015   xfree (dbs->want_lock_file);
1016   xfree (dbs);
1017   ctrl->tofu.dbs = NULL;
1018 }
1019
1020
1021 /* Collect results of a select min (foo) ...; style query.  Aborts if
1022    the argument is not a valid integer (or real of the form X.0).  */
1023 static int
1024 get_single_long_cb (void *cookie, int argc, char **argv, char **azColName)
1025 {
1026   long *count = cookie;
1027
1028   (void) azColName;
1029
1030   log_assert (argc == 1);
1031
1032   if (string_to_long (count, argv[0], 0, __LINE__))
1033     return 1; /* Abort.  */
1034
1035   return 0;
1036 }
1037
1038 static int
1039 get_single_long_cb2 (void *cookie, int argc, char **argv, char **azColName,
1040                      sqlite3_stmt *stmt)
1041 {
1042   (void) stmt;
1043   return get_single_long_cb (cookie, argc, argv, azColName);
1044 }
1045
1046 /* Record (or update) a trust policy about a (possibly new)
1047    binding.
1048
1049    If SHOW_OLD is set, the binding's old policy is displayed.  */
1050 static gpg_error_t
1051 record_binding (tofu_dbs_t dbs, const char *fingerprint, const char *email,
1052                 const char *user_id,
1053                 enum tofu_policy policy, enum tofu_policy effective_policy,
1054                 const char *conflict, int set_conflict,
1055                 int show_old, time_t now)
1056 {
1057   char *fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
1058   gpg_error_t rc;
1059   char *err = NULL;
1060
1061   if (! (policy == TOFU_POLICY_AUTO
1062          || policy == TOFU_POLICY_GOOD
1063          || policy == TOFU_POLICY_UNKNOWN
1064          || policy == TOFU_POLICY_BAD
1065          || policy == TOFU_POLICY_ASK))
1066     log_bug ("%s: Bad value for policy (%d)!\n", __func__, policy);
1067
1068
1069   if (DBG_TRUST || show_old)
1070     {
1071       /* Get the old policy.  Since this is just for informational
1072        * purposes, there is no need to start a transaction or to die
1073        * if there is a failure.  */
1074
1075       /* policy_old needs to be a long and not an enum tofu_policy,
1076          because we pass it by reference to get_single_long_cb2, which
1077          expects a long.  */
1078       long policy_old = TOFU_POLICY_NONE;
1079
1080       rc = gpgsql_stepx
1081         (dbs->db, &dbs->s.record_binding_get_old_policy,
1082          get_single_long_cb2, &policy_old, &err,
1083          "select policy from bindings where fingerprint = ? and email = ?",
1084          GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1085          GPGSQL_ARG_END);
1086       if (rc)
1087         {
1088           log_debug ("TOFU: Error reading from binding database"
1089                      " (reading policy for <key: %s, user id: %s>): %s\n",
1090                      fingerprint, email, err);
1091           sqlite3_free (err);
1092         }
1093
1094       if (policy_old != TOFU_POLICY_NONE)
1095         (show_old ? log_info : log_debug)
1096           ("Changing TOFU trust policy for binding"
1097            " <key: %s, user id: %s> from %s to %s.\n",
1098            fingerprint, show_old ? user_id : email,
1099            tofu_policy_str (policy_old),
1100            tofu_policy_str (policy));
1101       else
1102         (show_old ? log_info : log_debug)
1103           ("Setting TOFU trust policy for new binding"
1104            " <key: %s, user id: %s> to %s.\n",
1105            fingerprint, show_old ? user_id : email,
1106            tofu_policy_str (policy));
1107     }
1108
1109   if (opt.dry_run)
1110     {
1111       log_info ("TOFU database update skipped due to --dry-run\n");
1112       rc = 0;
1113       goto leave;
1114     }
1115
1116   rc = gpgsql_stepx
1117     (dbs->db, &dbs->s.record_binding_update, NULL, NULL, &err,
1118      "insert or replace into bindings\n"
1119      " (oid, fingerprint, email, user_id, time,"
1120      "  policy, conflict, effective_policy)\n"
1121      " values (\n"
1122      /* If we don't explicitly reuse the OID, then SQLite will
1123       * reallocate a new one.  We just need to search for the OID
1124       * based on the fingerprint and email since they are unique.  */
1125      "  (select oid from bindings where fingerprint = ? and email = ?),\n"
1126      "  ?, ?, ?, ?, ?,"
1127      /* If SET_CONFLICT is 0, then preserve conflict's current value.  */
1128      "  case ?"
1129      "    when 0 then"
1130      "      (select conflict from bindings where fingerprint = ? and email = ?)"
1131      "    else ?"
1132      "  end,"
1133      "  ?);",
1134      /* oid subquery.  */
1135      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1136      /* values 2 through 6.  */
1137      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1138      GPGSQL_ARG_STRING, user_id,
1139      GPGSQL_ARG_LONG_LONG, (long long) now,
1140      GPGSQL_ARG_INT, (int) policy,
1141      /* conflict subquery.  */
1142      GPGSQL_ARG_INT, set_conflict ? 1 : 0,
1143      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
1144      GPGSQL_ARG_STRING, conflict ? conflict : "",
1145      GPGSQL_ARG_INT, (int) effective_policy,
1146      GPGSQL_ARG_END);
1147   if (rc)
1148     {
1149       log_error (_("error updating TOFU database: %s\n"), err);
1150       print_further_info (" insert bindings <key: %s, user id: %s> = %s",
1151                           fingerprint, email, tofu_policy_str (policy));
1152       sqlite3_free (err);
1153       goto leave;
1154     }
1155
1156  leave:
1157   xfree (fingerprint_pp);
1158   return rc;
1159 }
1160
1161
1162 /* Collect the strings returned by a query in a simple string list.
1163    Any NULL values are converted to the empty string.
1164
1165    If a result has 3 rows and each row contains two columns, then the
1166    results are added to the list as follows (the value is parentheses
1167    is the 1-based index in the final list):
1168
1169      row 1, col 2 (6)
1170      row 1, col 1 (5)
1171      row 2, col 2 (4)
1172      row 2, col 1 (3)
1173      row 3, col 2 (2)
1174      row 3, col 1 (1)
1175
1176    This is because add_to_strlist pushes the results onto the front of
1177    the list.  The end result is that the rows are backwards, but the
1178    columns are in the expected order.  */
1179 static int
1180 strings_collect_cb (void *cookie, int argc, char **argv, char **azColName)
1181 {
1182   int i;
1183   strlist_t *strlist = cookie;
1184
1185   (void) azColName;
1186
1187   for (i = argc - 1; i >= 0; i --)
1188     add_to_strlist (strlist, argv[i] ? argv[i] : "");
1189
1190   return 0;
1191 }
1192
1193 static int
1194 strings_collect_cb2 (void *cookie, int argc, char **argv, char **azColName,
1195                      sqlite3_stmt *stmt)
1196 {
1197   (void) stmt;
1198   return strings_collect_cb (cookie, argc, argv, azColName);
1199
1200 }
1201
1202 /* Auxiliary data structure to collect statistics about
1203    signatures.  */
1204 struct signature_stats
1205 {
1206   struct signature_stats *next;
1207
1208   /* The user-assigned policy for this binding.  */
1209   enum tofu_policy policy;
1210
1211   /* How long ago the signature was created (rounded to a multiple of
1212      TIME_AGO_UNIT_SMALL, etc.).  */
1213   long time_ago;
1214   /* Number of signatures during this time.  */
1215   unsigned long count;
1216
1217   /* If the corresponding key/user id has been expired / revoked.  */
1218   int is_expired;
1219   int is_revoked;
1220
1221   /* The key that generated this signature.  */
1222   char fingerprint[1];
1223 };
1224
1225 static void
1226 signature_stats_free (struct signature_stats *stats)
1227 {
1228   while (stats)
1229     {
1230       struct signature_stats *next = stats->next;
1231       xfree (stats);
1232       stats = next;
1233     }
1234 }
1235
1236 static void
1237 signature_stats_prepend (struct signature_stats **statsp,
1238                          const char *fingerprint,
1239                          enum tofu_policy policy,
1240                          long time_ago,
1241                          unsigned long count)
1242 {
1243   struct signature_stats *stats =
1244     xmalloc_clear (sizeof (*stats) + strlen (fingerprint));
1245
1246   stats->next = *statsp;
1247   *statsp = stats;
1248
1249   strcpy (stats->fingerprint, fingerprint);
1250   stats->policy = policy;
1251   stats->time_ago = time_ago;
1252   stats->count = count;
1253 }
1254
1255
1256 /* Process rows that contain the four columns:
1257
1258      <fingerprint, policy, time ago, count>.  */
1259 static int
1260 signature_stats_collect_cb (void *cookie, int argc, char **argv,
1261                             char **azColName, sqlite3_stmt *stmt)
1262 {
1263   struct signature_stats **statsp = cookie;
1264   int i = 0;
1265   enum tofu_policy policy;
1266   long time_ago;
1267   unsigned long count;
1268   long along;
1269
1270   (void) azColName;
1271   (void) stmt;
1272
1273   i ++;
1274
1275   if (string_to_long (&along, argv[i], 0, __LINE__))
1276     return 1;  /* Abort */
1277   policy = along;
1278   i ++;
1279
1280   if (! argv[i])
1281     time_ago = 0;
1282   else
1283     {
1284       if (string_to_long (&time_ago, argv[i], 0, __LINE__))
1285         return 1; /* Abort.  */
1286     }
1287   i ++;
1288
1289   /* If time_ago is NULL, then we had no messages, but we still have a
1290      single row, which count(*) turns into 1.  */
1291   if (! argv[i - 1])
1292     count = 0;
1293   else
1294     {
1295       if (string_to_ulong (&count, argv[i], 0, __LINE__))
1296         return 1; /* Abort */
1297     }
1298   i ++;
1299
1300   log_assert (argc == i);
1301
1302   signature_stats_prepend (statsp, argv[0], policy, time_ago, count);
1303
1304   return 0;
1305 }
1306
1307 /* Format the first part of a conflict message and return that as a
1308  * malloced string.  */
1309 static char *
1310 format_conflict_msg_part1 (int policy, strlist_t conflict_set,
1311                            const char *email)
1312 {
1313   estream_t fp;
1314   char *fingerprint;
1315   char *tmpstr, *text;
1316
1317   log_assert (conflict_set);
1318   fingerprint = conflict_set->d;
1319
1320   fp = es_fopenmem (0, "rw,samethread");
1321   if (!fp)
1322     log_fatal ("error creating memory stream: %s\n",
1323                gpg_strerror (gpg_error_from_syserror()));
1324
1325   if (policy == TOFU_POLICY_NONE)
1326     {
1327       es_fprintf (fp,
1328                   _("This is the first time the email address \"%s\" is "
1329                     "being used with key %s."),
1330                   email, fingerprint);
1331       es_fputs ("  ", fp);
1332     }
1333   else if (policy == TOFU_POLICY_ASK && conflict_set->next)
1334     {
1335       int conflicts = strlist_length (conflict_set);
1336       es_fprintf
1337         (fp, ngettext("The email address \"%s\" is associated with %d key!",
1338                       "The email address \"%s\" is associated with %d keys!",
1339                       conflicts),
1340          email, conflicts);
1341       if (opt.verbose)
1342         es_fprintf (fp,
1343                     _("  Since this binding's policy was 'auto', it has been "
1344                       "changed to 'ask'."));
1345       es_fputs ("  ", fp);
1346     }
1347
1348   es_fprintf (fp,
1349               _("Please indicate whether this email address should"
1350                 " be associated with key %s or whether you think someone"
1351                 " is impersonating \"%s\"."),
1352               fingerprint, email);
1353   es_fputc ('\n', fp);
1354
1355   es_fputc (0, fp);
1356   if (es_fclose_snatch (fp, (void **)&tmpstr, NULL))
1357     log_fatal ("error snatching memory stream\n");
1358   text = format_text (tmpstr, 0, 72, 80);
1359   es_free (tmpstr);
1360
1361   return text;
1362 }
1363
1364
1365 /* Return 1 if A signed B and B signed A.  */
1366 static int
1367 cross_sigs (const char *email, kbnode_t a, kbnode_t b)
1368 {
1369   int i;
1370
1371   PKT_public_key *a_pk = a->pkt->pkt.public_key;
1372   PKT_public_key *b_pk = b->pkt->pkt.public_key;
1373
1374   char a_keyid[33];
1375   char b_keyid[33];
1376
1377   if (DBG_TRUST)
1378     {
1379       format_keyid (pk_main_keyid (a_pk),
1380                     KF_LONG, a_keyid, sizeof (a_keyid));
1381       format_keyid (pk_main_keyid (b_pk),
1382                     KF_LONG, b_keyid, sizeof (b_keyid));
1383     }
1384
1385   for (i = 0; i < 2; i ++)
1386     {
1387       /* See if SIGNER signed SIGNEE.  */
1388
1389       kbnode_t signer = i == 0 ? a : b;
1390       kbnode_t signee = i == 0 ? b : a;
1391
1392       PKT_public_key *signer_pk = signer->pkt->pkt.public_key;
1393       u32 *signer_kid = pk_main_keyid (signer_pk);
1394       kbnode_t n;
1395
1396       int saw_email = 0;
1397
1398       /* Iterate over SIGNEE's keyblock and see if there is a valid
1399          signature from SIGNER.  */
1400       for (n = signee; n; n = n->next)
1401         {
1402           PKT_signature *sig;
1403
1404           if (n->pkt->pkttype == PKT_USER_ID)
1405             {
1406               if (saw_email)
1407                 /* We're done: we've processed all signatures on the
1408                    user id.  */
1409                 break;
1410               else
1411                 {
1412                   /* See if this is the matching user id.  */
1413                   PKT_user_id *user_id = n->pkt->pkt.user_id;
1414                   char *email2 = email_from_user_id (user_id->name);
1415
1416                   if (strcmp (email, email2) == 0)
1417                     saw_email = 1;
1418
1419                   xfree (email2);
1420                 }
1421             }
1422
1423           if (! saw_email)
1424             continue;
1425
1426           if (n->pkt->pkttype != PKT_SIGNATURE)
1427             continue;
1428
1429           sig = n->pkt->pkt.signature;
1430
1431           if (! (sig->sig_class == 0x10
1432                  || sig->sig_class == 0x11
1433                  || sig->sig_class == 0x12
1434                  || sig->sig_class == 0x13))
1435             /* Not a signature over a user id.  */
1436             continue;
1437
1438           /* SIG is on SIGNEE's keyblock.  If SIG was generated by the
1439              signer, then it's a match.  */
1440           if (keyid_cmp (sig->keyid, signer_kid) == 0)
1441             /* Match!  */
1442             break;
1443         }
1444       if (! n)
1445         /* We didn't find a signature from signer over signee.  */
1446         {
1447           if (DBG_TRUST)
1448             log_debug ("No cross sig between %s and %s\n",
1449                        a_keyid, b_keyid);
1450           return 0;
1451         }
1452     }
1453
1454   /* A signed B and B signed A.  */
1455   if (DBG_TRUST)
1456     log_debug ("Cross sig between %s and %s\n",
1457                a_keyid, b_keyid);
1458
1459   return 1;
1460 }
1461
1462 /* Return whether the key was signed by an ultimately trusted key.  */
1463 static int
1464 signed_by_utk (const char *email, kbnode_t a)
1465 {
1466   kbnode_t n;
1467   int saw_email = 0;
1468
1469   for (n = a; n; n = n->next)
1470     {
1471       PKT_signature *sig;
1472
1473       if (n->pkt->pkttype == PKT_USER_ID)
1474         {
1475           if (saw_email)
1476             /* We're done: we've processed all signatures on the
1477                user id.  */
1478             break;
1479           else
1480             {
1481               /* See if this is the matching user id.  */
1482               PKT_user_id *user_id = n->pkt->pkt.user_id;
1483               char *email2 = email_from_user_id (user_id->name);
1484
1485               if (strcmp (email, email2) == 0)
1486                 saw_email = 1;
1487
1488               xfree (email2);
1489             }
1490         }
1491
1492       if (! saw_email)
1493         continue;
1494
1495       if (n->pkt->pkttype != PKT_SIGNATURE)
1496         continue;
1497
1498       sig = n->pkt->pkt.signature;
1499
1500       if (! (sig->sig_class == 0x10
1501              || sig->sig_class == 0x11
1502              || sig->sig_class == 0x12
1503              || sig->sig_class == 0x13))
1504         /* Not a signature over a user id.  */
1505         continue;
1506
1507       /* SIG is on SIGNEE's keyblock.  If SIG was generated by the
1508          signer, then it's a match.  */
1509       if (tdb_keyid_is_utk (sig->keyid))
1510         {
1511           /* Match!  */
1512           if (DBG_TRUST)
1513             log_debug ("TOFU: %s is signed by an ultimately trusted key.\n",
1514                        pk_keyid_str (a->pkt->pkt.public_key));
1515
1516           return 1;
1517         }
1518     }
1519
1520   if (DBG_TRUST)
1521     log_debug ("TOFU: %s is NOT signed by an ultimately trusted key.\n",
1522                pk_keyid_str (a->pkt->pkt.public_key));
1523
1524   return 0;
1525 }
1526
1527
1528 enum
1529   {
1530     BINDING_NEW = 1 << 0,
1531     BINDING_CONFLICT = 1 << 1,
1532     BINDING_EXPIRED = 1 << 2,
1533     BINDING_REVOKED = 1 << 3
1534   };
1535
1536
1537 /* Ask the user about the binding.  There are three ways we could end
1538  * up here:
1539  *
1540  *   - This is a new binding and there is a conflict
1541  *     (policy == TOFU_POLICY_NONE && conflict_set_count > 1),
1542  *
1543  *   - This is a new binding and opt.tofu_default_policy is set to
1544  *     ask.  (policy == TOFU_POLICY_NONE && opt.tofu_default_policy ==
1545  *     TOFU_POLICY_ASK), or,
1546  *
1547  *   - The policy is ask (the user deferred last time) (policy ==
1548  *     TOFU_POLICY_ASK).
1549  *
1550  * Note: this function must not be called while in a transaction!
1551  *
1552  * CONFLICT_SET includes all of the conflicting bindings
1553  * with FINGERPRINT first.  FLAGS is a bit-wise or of
1554  * BINDING_NEW, etc.
1555  */
1556 static void
1557 ask_about_binding (ctrl_t ctrl,
1558                    enum tofu_policy *policy,
1559                    int *trust_level,
1560                    strlist_t conflict_set,
1561                    const char *fingerprint,
1562                    const char *email,
1563                    const char *user_id,
1564                    time_t now)
1565 {
1566   tofu_dbs_t dbs;
1567   strlist_t iter;
1568   int conflict_set_count = strlist_length (conflict_set);
1569   char *sqerr = NULL;
1570   int rc;
1571   estream_t fp;
1572   strlist_t other_user_ids = NULL;
1573   struct signature_stats *stats = NULL;
1574   struct signature_stats *stats_iter = NULL;
1575   char *prompt = NULL;
1576   char *choices;
1577
1578   dbs = ctrl->tofu.dbs;
1579   log_assert (dbs);
1580   log_assert (dbs->in_transaction == 0);
1581
1582   fp = es_fopenmem (0, "rw,samethread");
1583   if (!fp)
1584     log_fatal ("error creating memory stream: %s\n",
1585                gpg_strerror (gpg_error_from_syserror()));
1586
1587   {
1588     char *text = format_conflict_msg_part1 (*policy, conflict_set, email);
1589     es_fputs (text, fp);
1590     es_fputc ('\n', fp);
1591     xfree (text);
1592   }
1593
1594   begin_transaction (ctrl, 0);
1595
1596   /* Find other user ids associated with this key and whether the
1597    * bindings are marked as good or bad.  */
1598   rc = gpgsql_stepx
1599     (dbs->db, &dbs->s.get_trust_gather_other_user_ids,
1600      strings_collect_cb2, &other_user_ids, &sqerr,
1601      "select user_id, policy from bindings where fingerprint = ?;",
1602      GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_END);
1603   if (rc)
1604     {
1605       log_error (_("error gathering other user IDs: %s\n"), sqerr);
1606       sqlite3_free (sqerr);
1607       sqerr = NULL;
1608       rc = gpg_error (GPG_ERR_GENERAL);
1609     }
1610
1611   if (other_user_ids)
1612     {
1613       strlist_t strlist_iter;
1614
1615       es_fprintf (fp, _("This key's user IDs:\n"));
1616       for (strlist_iter = other_user_ids;
1617            strlist_iter;
1618            strlist_iter = strlist_iter->next)
1619         {
1620           char *other_user_id = strlist_iter->d;
1621           char *other_thing;
1622           enum tofu_policy other_policy;
1623
1624           log_assert (strlist_iter->next);
1625           strlist_iter = strlist_iter->next;
1626           other_thing = strlist_iter->d;
1627
1628           other_policy = atoi (other_thing);
1629
1630           es_fprintf (fp, "  %s (", other_user_id);
1631           es_fprintf (fp, _("policy: %s"), tofu_policy_str (other_policy));
1632           es_fprintf (fp, ")\n");
1633         }
1634       es_fprintf (fp, "\n");
1635
1636       free_strlist (other_user_ids);
1637     }
1638
1639   /* Get the stats for all the keys in CONFLICT_SET.  */
1640   strlist_rev (&conflict_set);
1641   for (iter = conflict_set; iter && ! rc; iter = iter->next)
1642     {
1643 #define STATS_SQL(table, time, sign)                         \
1644          "select fingerprint, policy, time_ago, count(*)\n" \
1645          " from\n" \
1646          "  (select bindings.*,\n" \
1647          "     "sign" case\n" \
1648          "       when delta ISNULL then 1\n" \
1649          /* From the future (but if its just a couple of hours in the \
1650           * future don't turn it into a warning)?  Or should we use \
1651           * small, medium or large units?  (Note: whatever we do, we \
1652           * keep the value in seconds.  Then when we group, everything \
1653           * that rounds to the same number of seconds is grouped.)  */ \
1654          "      when delta < -("STRINGIFY (TIME_AGO_FUTURE_IGNORE)") then 2\n" \
1655          "      when delta < ("STRINGIFY (TIME_AGO_SMALL_THRESHOLD)")\n" \
1656          "       then 3\n" \
1657          "      when delta < ("STRINGIFY (TIME_AGO_MEDIUM_THRESHOLD)")\n" \
1658          "       then 4\n" \
1659          "      when delta < ("STRINGIFY (TIME_AGO_LARGE_THRESHOLD)")\n" \
1660          "       then 5\n" \
1661          "      else 6\n" \
1662          "     end time_ago,\n" \
1663          "    delta time_ago_raw\n" \
1664          "   from bindings\n" \
1665          "   left join\n" \
1666          "     (select *,\n" \
1667          "        cast(? - " time " as real) delta\n" \
1668          "       from " table ") ss\n" \
1669          "    on ss.binding = bindings.oid)\n" \
1670          " where email = ? and fingerprint = ?\n" \
1671          " group by time_ago\n" \
1672          /* Make sure the current key is first.  */ \
1673          " order by time_ago desc;\n"
1674
1675       /* Use the time when we saw the signature, not when the
1676          signature was created as that can be forged.  */
1677       rc = gpgsql_stepx
1678         (dbs->db, &dbs->s.get_trust_gather_signature_stats,
1679          signature_stats_collect_cb, &stats, &sqerr,
1680          STATS_SQL ("signatures", "time", ""),
1681          GPGSQL_ARG_LONG_LONG, (long long) now,
1682          GPGSQL_ARG_STRING, email,
1683          GPGSQL_ARG_STRING, iter->d,
1684          GPGSQL_ARG_END);
1685       if (rc)
1686         {
1687           rc = gpg_error (GPG_ERR_GENERAL);
1688           break;
1689         }
1690
1691       if (!stats || strcmp (iter->d, stats->fingerprint) != 0)
1692         /* No stats for this binding.  Add a dummy entry.  */
1693         signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, 1, 1);
1694
1695       rc = gpgsql_stepx
1696         (dbs->db, &dbs->s.get_trust_gather_encryption_stats,
1697          signature_stats_collect_cb, &stats, &sqerr,
1698          STATS_SQL ("encryptions", "time", "-"),
1699          GPGSQL_ARG_LONG_LONG, (long long) now,
1700          GPGSQL_ARG_STRING, email,
1701          GPGSQL_ARG_STRING, iter->d,
1702          GPGSQL_ARG_END);
1703       if (rc)
1704         {
1705           rc = gpg_error (GPG_ERR_GENERAL);
1706           break;
1707         }
1708
1709 #undef STATS_SQL
1710
1711       if (!stats || strcmp (iter->d, stats->fingerprint) != 0
1712           || stats->time_ago > 0)
1713         /* No stats for this binding.  Add a dummy entry.  */
1714         signature_stats_prepend (&stats, iter->d, TOFU_POLICY_AUTO, -1, 1);
1715     }
1716   end_transaction (ctrl, 0);
1717   strlist_rev (&conflict_set);
1718   if (rc)
1719     {
1720       strlist_t strlist_iter;
1721
1722       log_error (_("error gathering signature stats: %s\n"), sqerr);
1723       sqlite3_free (sqerr);
1724       sqerr = NULL;
1725
1726       es_fprintf (fp, ngettext("The email address \"%s\" is"
1727                                " associated with %d key:\n",
1728                                "The email address \"%s\" is"
1729                                " associated with %d keys:\n",
1730                                conflict_set_count),
1731                   email, conflict_set_count);
1732       for (strlist_iter = conflict_set;
1733            strlist_iter;
1734            strlist_iter = strlist_iter->next)
1735         es_fprintf (fp, "  %s\n", strlist_iter->d);
1736     }
1737   else
1738     {
1739       char *key = NULL;
1740       strlist_t binding;
1741       int seen_in_past = 0;
1742       int encrypted = 1;
1743
1744       es_fprintf (fp, _("Statistics for keys"
1745                         " with the email address \"%s\":\n"),
1746                   email);
1747       for (stats_iter = stats; stats_iter; stats_iter = stats_iter->next)
1748         {
1749 #if 0
1750           log_debug ("%s: time_ago: %ld; count: %ld\n",
1751                      stats_iter->fingerprint,
1752                      stats_iter->time_ago,
1753                      stats_iter->count);
1754 #endif
1755
1756           if (stats_iter->time_ago > 0 && encrypted)
1757             {
1758               /* We've change from the encrypted stats to the verified
1759                * stats.  Reset SEEN_IN_PAST.  */
1760               encrypted = 0;
1761               seen_in_past = 0;
1762             }
1763
1764           if (! key || strcmp (key, stats_iter->fingerprint))
1765             {
1766               int this_key;
1767               char *key_pp;
1768
1769               key = stats_iter->fingerprint;
1770               this_key = strcmp (key, fingerprint) == 0;
1771               key_pp = format_hexfingerprint (key, NULL, 0);
1772               es_fprintf (fp, "  %s (", key_pp);
1773
1774               /* Find the associated binding.  */
1775               for (binding = conflict_set;
1776                    binding;
1777                    binding = binding->next)
1778                 if (strcmp (key, binding->d) == 0)
1779                   break;
1780               log_assert (binding);
1781
1782               if ((binding->flags & BINDING_REVOKED))
1783                 {
1784                   es_fprintf (fp, _("revoked"));
1785                   es_fprintf (fp, _(", "));
1786                 }
1787               else if ((binding->flags & BINDING_EXPIRED))
1788                 {
1789                   es_fprintf (fp, _("expired"));
1790                   es_fprintf (fp, _(", "));
1791                 }
1792
1793               if (this_key)
1794                 es_fprintf (fp, _("this key"));
1795               else
1796                 es_fprintf (fp, _("policy: %s"),
1797                             tofu_policy_str (stats_iter->policy));
1798               es_fputs ("):\n", fp);
1799               xfree (key_pp);
1800
1801               seen_in_past = 0;
1802
1803               show_statistics (dbs, stats_iter->fingerprint, email,
1804                                TOFU_POLICY_ASK, NULL, 1, now);
1805             }
1806
1807           if (labs(stats_iter->time_ago) == 1)
1808             {
1809               /* The 1 in this case is the NULL entry.  */
1810               log_assert (stats_iter->count == 1);
1811               stats_iter->count = 0;
1812             }
1813           seen_in_past += stats_iter->count;
1814
1815           es_fputs ("    ", fp);
1816
1817           if (!stats_iter->count)
1818             {
1819               if (stats_iter->time_ago > 0)
1820                 es_fprintf (fp, ngettext("Verified %d message.",
1821                                          "Verified %d messages.",
1822                                          seen_in_past), seen_in_past);
1823               else
1824                 es_fprintf (fp, ngettext("Encrypted %d message.",
1825                                          "Encrypted %d messages.",
1826                                          seen_in_past), seen_in_past);
1827             }
1828           else if (labs(stats_iter->time_ago) == 2)
1829             {
1830               if (stats_iter->time_ago > 0)
1831                 es_fprintf (fp, ngettext("Verified %d message in the future.",
1832                                          "Verified %d messages in the future.",
1833                                          seen_in_past), seen_in_past);
1834               else
1835                 es_fprintf (fp, ngettext("Encrypted %d message in the future.",
1836                                          "Encrypted %d messages in the future.",
1837                                          seen_in_past), seen_in_past);
1838               /* Reset it.  */
1839               seen_in_past = 0;
1840             }
1841           else
1842             {
1843               if (labs(stats_iter->time_ago) == 3)
1844                 {
1845                   int days = 1 + stats_iter->time_ago / TIME_AGO_UNIT_SMALL;
1846                   if (stats_iter->time_ago > 0)
1847                     es_fprintf
1848                       (fp,
1849                        ngettext("Messages verified over the past %d day: %d.",
1850                                 "Messages verified over the past %d days: %d.",
1851                                 days), days, seen_in_past);
1852                   else
1853                     es_fprintf
1854                       (fp,
1855                        ngettext("Messages encrypted over the past %d day: %d.",
1856                                 "Messages encrypted over the past %d days: %d.",
1857                                 days), days, seen_in_past);
1858                 }
1859               else if (labs(stats_iter->time_ago) == 4)
1860                 {
1861                   int months = 1 + stats_iter->time_ago / TIME_AGO_UNIT_MEDIUM;
1862                   if (stats_iter->time_ago > 0)
1863                     es_fprintf
1864                       (fp,
1865                        ngettext("Messages verified over the past %d month: %d.",
1866                                 "Messages verified over the past %d months: %d.",
1867                                 months), months, seen_in_past);
1868                   else
1869                     es_fprintf
1870                       (fp,
1871                        ngettext("Messages encrypted over the past %d month: %d.",
1872                                 "Messages encrypted over the past %d months: %d.",
1873                                 months), months, seen_in_past);
1874                 }
1875               else if (labs(stats_iter->time_ago) == 5)
1876                 {
1877                   int years = 1 + stats_iter->time_ago / TIME_AGO_UNIT_LARGE;
1878                   if (stats_iter->time_ago > 0)
1879                     es_fprintf
1880                       (fp,
1881                        ngettext("Messages verified over the past %d year: %d.",
1882                                 "Messages verified over the past %d years: %d.",
1883                                 years), years, seen_in_past);
1884                   else
1885                     es_fprintf
1886                       (fp,
1887                        ngettext("Messages encrypted over the past %d year: %d.",
1888                                 "Messages encrypted over the past %d years: %d.",
1889                                 years), years, seen_in_past);
1890                 }
1891               else if (labs(stats_iter->time_ago) == 6)
1892                 {
1893                   if (stats_iter->time_ago > 0)
1894                     es_fprintf
1895                       (fp, _("Messages verified in the past: %d."),
1896                        seen_in_past);
1897                   else
1898                     es_fprintf
1899                       (fp, _("Messages encrypted in the past: %d."),
1900                        seen_in_past);
1901                 }
1902               else
1903                 log_assert (! "Broken SQL.\n");
1904             }
1905           es_fputs ("\n", fp);
1906         }
1907     }
1908
1909   if (conflict_set_count > 1 || (conflict_set->flags & BINDING_CONFLICT))
1910     {
1911       /* This is a conflict.  */
1912
1913       /* TRANSLATORS: Please translate the text found in the source
1914        * file below.  We don't directly internationalize that text so
1915        * that we can tweak it without breaking translations.  */
1916       char *text = _("TOFU detected a binding conflict");
1917       char *textbuf;
1918       if (!strcmp (text, "TOFU detected a binding conflict"))
1919         {
1920           /* No translation.  Use the English text.  */
1921           text =
1922             "Normally, an email address is associated with a single key.  "
1923             "However, people sometimes generate a new key if "
1924             "their key is too old or they think it might be compromised.  "
1925             "Alternatively, a new key may indicate a man-in-the-middle "
1926             "attack!  Before accepting this association, you should talk to or "
1927             "call the person to make sure this new key is legitimate.";
1928         }
1929       textbuf = format_text (text, 0, 72, 80);
1930       es_fprintf (fp, "\n%s\n", textbuf);
1931       xfree (textbuf);
1932     }
1933
1934   es_fputc ('\n', fp);
1935
1936   /* Add a NUL terminator.  */
1937   es_fputc (0, fp);
1938   if (es_fclose_snatch (fp, (void **) &prompt, NULL))
1939     log_fatal ("error snatching memory stream\n");
1940
1941   /* I think showing the large message once is sufficient.  If we
1942    * would move it right before the cpr_get many lines will scroll
1943    * away and the user might not realize that he merely entered a
1944    * wrong choise (because he does not see that either).  As a small
1945    * benefit we allow C-L to redisplay everything.  */
1946   tty_printf ("%s", prompt);
1947
1948   /* Suspend any transaction: it could take a while until the user
1949      responds.  */
1950   tofu_suspend_batch_transaction (ctrl);
1951   while (1)
1952     {
1953       char *response;
1954
1955       /* TRANSLATORS: Two letters (normally the lower and upper case
1956        * version of the hotkey) for each of the five choices.  If
1957        * there is only one choice in your language, repeat it.  */
1958       choices = _("gG" "aA" "uU" "rR" "bB");
1959       if (strlen (choices) != 10)
1960         log_bug ("Bad TOFU conflict translation!  Please report.");
1961
1962       response = cpr_get
1963         ("tofu.conflict",
1964          _("(G)ood, (A)ccept once, (U)nknown, (R)eject once, (B)ad? "));
1965       trim_spaces (response);
1966       cpr_kill_prompt ();
1967       if (*response == CONTROL_L)
1968         tty_printf ("%s", prompt);
1969       else if (!response[0])
1970         /* Default to unknown.  Don't save it.  */
1971         {
1972           tty_printf (_("Defaulting to unknown.\n"));
1973           *policy = TOFU_POLICY_UNKNOWN;
1974           break;
1975         }
1976       else if (!response[1])
1977         {
1978           char *choice = strchr (choices, *response);
1979
1980           if (choice)
1981             {
1982               int c = ((size_t) choice - (size_t) choices) / 2;
1983
1984               switch (c)
1985                 {
1986                 case 0: /* Good.  */
1987                   *policy = TOFU_POLICY_GOOD;
1988                   *trust_level = tofu_policy_to_trust_level (*policy);
1989                   break;
1990                 case 1: /* Accept once.  */
1991                   *policy = TOFU_POLICY_ASK;
1992                   *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_GOOD);
1993                   break;
1994                 case 2: /* Unknown.  */
1995                   *policy = TOFU_POLICY_UNKNOWN;
1996                   *trust_level = tofu_policy_to_trust_level (*policy);
1997                   break;
1998                 case 3: /* Reject once.  */
1999                   *policy = TOFU_POLICY_ASK;
2000                   *trust_level = tofu_policy_to_trust_level (TOFU_POLICY_BAD);
2001                   break;
2002                 case 4: /* Bad.  */
2003                   *policy = TOFU_POLICY_BAD;
2004                   *trust_level = tofu_policy_to_trust_level (*policy);
2005                   break;
2006                 default:
2007                   log_bug ("c should be between 0 and 4 but it is %d!", c);
2008                 }
2009
2010               if (record_binding (dbs, fingerprint, email, user_id,
2011                                   *policy, TOFU_POLICY_NONE, NULL, 0, 0, now))
2012                 {
2013                   /* If there's an error registering the
2014                    * binding, don't save the signature.  */
2015                   *trust_level = _tofu_GET_TRUST_ERROR;
2016                 }
2017               break;
2018             }
2019         }
2020       xfree (response);
2021     }
2022
2023   tofu_resume_batch_transaction (ctrl);
2024
2025   xfree (prompt);
2026
2027   signature_stats_free (stats);
2028 }
2029
2030 /* Return the set of keys that conflict with the binding <fingerprint,
2031    email> (including the binding itself, which will be first in the
2032    list).  For each returned key also sets BINDING_NEW, etc.  */
2033 static strlist_t
2034 build_conflict_set (tofu_dbs_t dbs,
2035                     PKT_public_key *pk, const char *fingerprint,
2036                     const char *email)
2037 {
2038   gpg_error_t rc;
2039   char *sqerr;
2040   strlist_t conflict_set = NULL;
2041   int conflict_set_count;
2042   strlist_t iter;
2043   kbnode_t *kb_all;
2044   KEYDB_HANDLE hd;
2045   int i;
2046
2047   /* Get the fingerprints of any bindings that share the email address
2048    * and whether the bindings have a known conflict.
2049    *
2050    * Note: if the binding in question is in the DB, it will also be
2051    * returned.  Thus, if the result set is empty, then <email,
2052    * fingerprint> is a new binding.  */
2053   rc = gpgsql_stepx
2054     (dbs->db, &dbs->s.get_trust_bindings_with_this_email,
2055      strings_collect_cb2, &conflict_set, &sqerr,
2056      "select"
2057      /* A binding should only appear once, but try not to break in the
2058       * case of corruption.  */
2059      "  fingerprint || case sum(conflict NOTNULL) when 0 then '' else '!' end"
2060      " from bindings where email = ?"
2061      "  group by fingerprint"
2062      /* Make sure the current key comes first in the result list (if
2063         it is present).  */
2064      "  order by fingerprint = ? asc, fingerprint desc;",
2065      GPGSQL_ARG_STRING, email,
2066      GPGSQL_ARG_STRING, fingerprint,
2067      GPGSQL_ARG_END);
2068   if (rc)
2069     {
2070       log_error (_("error reading TOFU database: %s\n"), sqerr);
2071       print_further_info ("listing fingerprints");
2072       sqlite3_free (sqerr);
2073       rc = gpg_error (GPG_ERR_GENERAL);
2074       return NULL;
2075     }
2076
2077   /* Set BINDING_CONFLICT if the binding has a known conflict.  This
2078    * allows us to distinguish between bindings where the user
2079    * explicitly set the policy to ask and bindings where we set the
2080    * policy to ask due to a conflict.  */
2081   for (iter = conflict_set; iter; iter = iter->next)
2082     {
2083       int l = strlen (iter->d);
2084       if (!(l == 2 * MAX_FINGERPRINT_LEN
2085             || l == 2 * MAX_FINGERPRINT_LEN + 1))
2086         {
2087           log_error (_("TOFU db corruption detected.\n"));
2088           print_further_info ("fingerprint '%s' is not %d characters long",
2089                               iter->d, 2 * MAX_FINGERPRINT_LEN);
2090         }
2091
2092       if (l >= 1 && iter->d[l - 1] == '!')
2093         {
2094           iter->flags |= BINDING_CONFLICT;
2095           /* Remove the !.  */
2096           iter->d[l - 1] = 0;
2097         }
2098     }
2099
2100   /* If the current binding has not yet been recorded, add it to the
2101    * list.  (The order by above ensures that if it is present, it will
2102    * be first.)  */
2103   if (! (conflict_set && strcmp (conflict_set->d, fingerprint) == 0))
2104     {
2105       add_to_strlist (&conflict_set, fingerprint);
2106       conflict_set->flags |= BINDING_NEW;
2107     }
2108
2109   conflict_set_count = strlist_length (conflict_set);
2110
2111   /* Eliminate false conflicts.  */
2112
2113   if (conflict_set_count == 1)
2114     /* We only have a single key.  There are no false conflicts to
2115        eliminate.  But, we do need to set the flags.  */
2116     {
2117       if (pk->has_expired)
2118         conflict_set->flags |= BINDING_EXPIRED;
2119       if (pk->flags.revoked)
2120         conflict_set->flags |= BINDING_REVOKED;
2121
2122       return conflict_set;
2123     }
2124
2125   /* If two keys have cross signatures, then they are controlled by
2126    * the same person and thus are not in conflict.  */
2127   kb_all = xcalloc (sizeof (kb_all[0]), conflict_set_count);
2128   hd = keydb_new ();
2129   for (i = 0, iter = conflict_set;
2130        i < conflict_set_count;
2131        i ++, iter = iter->next)
2132     {
2133       char *fp = iter->d;
2134       KEYDB_SEARCH_DESC desc;
2135       kbnode_t kb;
2136       PKT_public_key *binding_pk;
2137       kbnode_t n;
2138       int found_user_id;
2139
2140       rc = keydb_search_reset (hd);
2141       if (rc)
2142         {
2143           log_error (_("resetting keydb: %s\n"),
2144                      gpg_strerror (rc));
2145           continue;
2146         }
2147
2148       rc = classify_user_id (fp, &desc, 0);
2149       if (rc)
2150         {
2151           log_error (_("error parsing key specification '%s': %s\n"),
2152                      fp, gpg_strerror (rc));
2153           continue;
2154         }
2155
2156       rc = keydb_search (hd, &desc, 1, NULL);
2157       if (rc)
2158         {
2159           /* Note: it is entirely possible that we don't have the key
2160              corresponding to an entry in the TOFU DB.  This can
2161              happen if we merge two TOFU DBs, but not the key
2162              rings.  */
2163           log_info (_("key \"%s\" not found: %s\n"),
2164                     fp, gpg_strerror (rc));
2165           continue;
2166         }
2167
2168       rc = keydb_get_keyblock (hd, &kb);
2169       if (rc)
2170         {
2171           log_error (_("error reading keyblock: %s\n"),
2172                      gpg_strerror (rc));
2173           print_further_info ("fingerprint: %s", fp);
2174           continue;
2175         }
2176
2177       merge_keys_and_selfsig (kb);
2178
2179       log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
2180
2181       kb_all[i] = kb;
2182
2183       /* Since we have the key block, use this opportunity to figure
2184        * out if the binding is expired or revoked.  */
2185       binding_pk = kb->pkt->pkt.public_key;
2186
2187       /* The binding is always expired/revoked if the key is
2188        * expired/revoked.  */
2189       if (binding_pk->has_expired)
2190         iter->flags |= BINDING_EXPIRED;
2191       if (binding_pk->flags.revoked)
2192         iter->flags |= BINDING_REVOKED;
2193
2194       /* The binding is also expired/revoked if the user id is
2195        * expired/revoked.  */
2196       n = kb;
2197       found_user_id = 0;
2198       while ((n = find_next_kbnode (n, PKT_USER_ID)) && ! found_user_id)
2199         {
2200           PKT_user_id *user_id2 = n->pkt->pkt.user_id;
2201           char *email2;
2202
2203           if (user_id2->attrib_data)
2204             continue;
2205
2206           email2 = email_from_user_id (user_id2->name);
2207
2208           if (strcmp (email, email2) == 0)
2209             {
2210               found_user_id = 1;
2211
2212               if (user_id2->is_revoked)
2213                 iter->flags |= BINDING_REVOKED;
2214               if (user_id2->is_expired)
2215                 iter->flags |= BINDING_EXPIRED;
2216             }
2217
2218           xfree (email2);
2219         }
2220
2221       if (! found_user_id)
2222         {
2223           log_info (_("TOFU db corruption detected.\n"));
2224           print_further_info ("user id '%s' not on key block '%s'",
2225                               email, fingerprint);
2226         }
2227     }
2228   keydb_release (hd);
2229
2230   /* Now that we have the key blocks, check for cross sigs.  */
2231   {
2232     int j;
2233     strlist_t *prevp;
2234     strlist_t iter_next;
2235     int *die;
2236
2237     log_assert (conflict_set_count > 0);
2238     die = xtrycalloc (conflict_set_count, sizeof *die);
2239     if (!die)
2240       {
2241         /*err = gpg_error_from_syserror ();*/
2242         xoutofcore (); /* Fixme: Let the fucntion return an error.  */
2243       }
2244
2245     for (i = 0; i < conflict_set_count; i ++)
2246       {
2247         /* Look for cross sigs between this key (i == 0) or a key
2248          * that has cross sigs with i == 0 (i.e., transitively) */
2249         if (! (i == 0 || die[i]))
2250           continue;
2251
2252         for (j = i + 1; j < conflict_set_count; j ++)
2253           /* Be careful: we might not have a key block for a key.  */
2254           if (kb_all[i] && kb_all[j] && cross_sigs (email, kb_all[i], kb_all[j]))
2255             die[j] = 1;
2256       }
2257
2258     /* Free unconflicting bindings (and all of the key blocks).  */
2259     for (iter = conflict_set, prevp = &conflict_set, i = 0;
2260          iter;
2261          iter = iter_next, i ++)
2262       {
2263         iter_next = iter->next;
2264
2265         release_kbnode (kb_all[i]);
2266
2267         if (die[i])
2268           {
2269             *prevp = iter_next;
2270             iter->next = NULL;
2271             free_strlist (iter);
2272             conflict_set_count --;
2273           }
2274         else
2275           {
2276             prevp = &iter->next;
2277           }
2278       }
2279
2280     /* We shouldn't have removed the head.  */
2281     log_assert (conflict_set);
2282     log_assert (conflict_set_count >= 1);
2283     xfree (die);
2284   }
2285   xfree (kb_all);
2286
2287   if (DBG_TRUST)
2288     {
2289       log_debug ("binding <key: %s, email: %s> conflicts:\n",
2290                  fingerprint, email);
2291       for (iter = conflict_set; iter; iter = iter->next)
2292         {
2293           log_debug ("  %s:%s%s%s%s\n",
2294                      iter->d,
2295                      (iter->flags & BINDING_NEW) ? " new" : "",
2296                      (iter->flags & BINDING_CONFLICT) ? " known_conflict" : "",
2297                      (iter->flags & BINDING_EXPIRED) ? " expired" : "",
2298                      (iter->flags & BINDING_REVOKED) ? " revoked" : "");
2299         }
2300     }
2301
2302   return conflict_set;
2303 }
2304
2305
2306 /* Return the effective policy for the binding <FINGERPRINT, EMAIL>
2307  * (email has already been normalized).  Returns
2308  * _tofu_GET_POLICY_ERROR if an error occurs.  Returns any conflict
2309  * information in *CONFLICT_SETP if CONFLICT_SETP is not NULL and the
2310  * returned policy is TOFU_POLICY_ASK (consequently, if there is a
2311  * conflict, but the user set the policy to good *CONFLICT_SETP will
2312  * empty).  Note: as per build_conflict_set, which is used to build
2313  * the conflict information, the conflict information includes the
2314  * current user id as the first element of the linked list.
2315  *
2316  * This function registers the binding in the bindings table if it has
2317  * not yet been registered.
2318  */
2319 static enum tofu_policy
2320 get_policy (tofu_dbs_t dbs, PKT_public_key *pk,
2321             const char *fingerprint, const char *user_id, const char *email,
2322             strlist_t *conflict_setp, time_t now)
2323 {
2324   int rc;
2325   char *err = NULL;
2326   strlist_t results = NULL;
2327   enum tofu_policy policy = _tofu_GET_POLICY_ERROR;
2328   enum tofu_policy effective_policy_orig = TOFU_POLICY_NONE;
2329   enum tofu_policy effective_policy = _tofu_GET_POLICY_ERROR;
2330   long along;
2331   char *conflict_orig = NULL;
2332   char *conflict = NULL;
2333   strlist_t conflict_set = NULL;
2334   int conflict_set_count;
2335
2336   /* Check if the <FINGERPRINT, EMAIL> binding is known
2337      (TOFU_POLICY_NONE cannot appear in the DB.  Thus, if POLICY is
2338      still TOFU_POLICY_NONE after executing the query, then the
2339      result set was empty.)  */
2340   rc = gpgsql_stepx (dbs->db, &dbs->s.get_policy_select_policy_and_conflict,
2341                       strings_collect_cb2, &results, &err,
2342                       "select policy, conflict, effective_policy from bindings\n"
2343                       " where fingerprint = ? and email = ?",
2344                       GPGSQL_ARG_STRING, fingerprint,
2345                       GPGSQL_ARG_STRING, email,
2346                       GPGSQL_ARG_END);
2347   if (rc)
2348     {
2349       log_error (_("error reading TOFU database: %s\n"), err);
2350       print_further_info ("reading the policy");
2351       sqlite3_free (err);
2352       rc = gpg_error (GPG_ERR_GENERAL);
2353       goto out;
2354     }
2355
2356   if (strlist_length (results) == 0)
2357     {
2358       /* No results.  Use the defaults.  */
2359       policy = TOFU_POLICY_NONE;
2360       effective_policy = TOFU_POLICY_NONE;
2361     }
2362   else if (strlist_length (results) == 3)
2363     {
2364       /* Parse and sanity check the results.  */
2365
2366       if (string_to_long (&along, results->d, 0, __LINE__))
2367         {
2368           log_error (_("error reading TOFU database: %s\n"),
2369                      gpg_strerror (GPG_ERR_BAD_DATA));
2370           print_further_info ("bad value for policy: %s", results->d);
2371           goto out;
2372         }
2373       policy = along;
2374
2375       if (! (policy == TOFU_POLICY_AUTO
2376              || policy == TOFU_POLICY_GOOD
2377              || policy == TOFU_POLICY_UNKNOWN
2378              || policy == TOFU_POLICY_BAD
2379              || policy == TOFU_POLICY_ASK))
2380         {
2381           log_error (_("error reading TOFU database: %s\n"),
2382                      gpg_strerror (GPG_ERR_DB_CORRUPTED));
2383           print_further_info ("invalid value for policy (%d)", policy);
2384           effective_policy = _tofu_GET_POLICY_ERROR;
2385           goto out;
2386         }
2387
2388       if (*results->next->d)
2389         conflict = xstrdup (results->next->d);
2390
2391       if (string_to_long (&along, results->next->next->d, 0, __LINE__))
2392         {
2393           log_error (_("error reading TOFU database: %s\n"),
2394                      gpg_strerror (GPG_ERR_BAD_DATA));
2395           print_further_info ("bad value for effective policy: %s",
2396                               results->next->next->d);
2397           goto out;
2398         }
2399       effective_policy = along;
2400
2401       if (! (effective_policy == TOFU_POLICY_NONE
2402              || effective_policy == TOFU_POLICY_AUTO
2403              || effective_policy == TOFU_POLICY_GOOD
2404              || effective_policy == TOFU_POLICY_UNKNOWN
2405              || effective_policy == TOFU_POLICY_BAD
2406              || effective_policy == TOFU_POLICY_ASK))
2407         {
2408           log_error (_("error reading TOFU database: %s\n"),
2409                      gpg_strerror (GPG_ERR_DB_CORRUPTED));
2410           print_further_info ("invalid value for effective_policy (%d)",
2411                               effective_policy);
2412           effective_policy = _tofu_GET_POLICY_ERROR;
2413           goto out;
2414         }
2415     }
2416   else
2417     {
2418       /* The result has the wrong form.  */
2419
2420       log_error (_("error reading TOFU database: %s\n"),
2421                  gpg_strerror (GPG_ERR_BAD_DATA));
2422       print_further_info ("reading policy: expected 3 columns, got %d\n",
2423                           strlist_length (results));
2424       goto out;
2425     }
2426
2427   /* Save the effective policy and conflict so we know if we changed
2428    * them.  */
2429   effective_policy_orig = effective_policy;
2430   conflict_orig = conflict;
2431
2432   /* Unless there is a conflict, if the effective policy is cached,
2433    * just return it.  The reason we don't do this when there is a
2434    * conflict is because of the following scenario: assume A and B
2435    * conflict and B has signed A's key.  Now, later we import A's
2436    * signature on B.  We need to recheck A, but the signature was on
2437    * B, i.e., when B changes, we invalidate B's effective policy, but
2438    * we also need to invalidate A's effective policy.  Instead, we
2439    * assume that conflicts are rare and don't optimize for them, which
2440    * would complicate the code.  */
2441   if (effective_policy != TOFU_POLICY_NONE && !conflict)
2442     goto out;
2443
2444   /* If the user explicitly set the policy, then respect that.  */
2445   if (policy != TOFU_POLICY_AUTO && policy != TOFU_POLICY_NONE)
2446     {
2447       effective_policy = policy;
2448       goto out;
2449     }
2450
2451   /* Unless proven wrong, assume the effective policy is 'auto'.  */
2452   effective_policy = TOFU_POLICY_AUTO;
2453
2454   /* See if the key is ultimately trusted.  */
2455   {
2456     u32 kid[2];
2457
2458     keyid_from_pk (pk, kid);
2459     if (tdb_keyid_is_utk (kid))
2460       {
2461         effective_policy = TOFU_POLICY_GOOD;
2462         goto out;
2463       }
2464   }
2465
2466   /* See if the key is signed by an ultimately trusted key.  */
2467   {
2468     int fingerprint_raw_len = strlen (fingerprint) / 2;
2469     char fingerprint_raw[20];
2470     int len = 0;
2471
2472     if (fingerprint_raw_len != sizeof fingerprint_raw
2473         || ((len = hex2bin (fingerprint,
2474                             fingerprint_raw, fingerprint_raw_len))
2475             != strlen (fingerprint)))
2476       {
2477         if (DBG_TRUST)
2478           log_debug ("TOFU: Bad fingerprint: %s (len: %zu, parsed: %d)\n",
2479                      fingerprint, strlen (fingerprint), len);
2480       }
2481     else
2482       {
2483         int lookup_err;
2484         kbnode_t kb;
2485
2486         lookup_err = get_pubkey_byfprint (NULL, &kb,
2487                                           fingerprint_raw,
2488                                           fingerprint_raw_len);
2489         if (lookup_err)
2490           {
2491             if (DBG_TRUST)
2492               log_debug ("TOFU: Looking up %s: %s\n",
2493                          fingerprint, gpg_strerror (lookup_err));
2494           }
2495         else
2496           {
2497             int is_signed_by_utk = signed_by_utk (email, kb);
2498             release_kbnode (kb);
2499             if (is_signed_by_utk)
2500               {
2501                 effective_policy = TOFU_POLICY_GOOD;
2502                 goto out;
2503               }
2504           }
2505       }
2506   }
2507
2508   /* Check for any conflicts / see if a previously discovered conflict
2509    * disappeared.  The latter can happen if the conflicting bindings
2510    * are now cross signed, for instance.  */
2511
2512   conflict_set = build_conflict_set (dbs, pk, fingerprint, email);
2513   conflict_set_count = strlist_length (conflict_set);
2514   if (conflict_set_count == 0)
2515     {
2516       /* build_conflict_set should always at least return the current
2517          binding.  Something went wrong.  */
2518       effective_policy = _tofu_GET_POLICY_ERROR;
2519       goto out;
2520     }
2521
2522   if (conflict_set_count == 1
2523       && (conflict_set->flags & BINDING_NEW))
2524     {
2525       /* We've never observed a binding with this email address and we
2526        * have a default policy, which is not to ask the user.  */
2527
2528       /* If we've seen this binding, then we've seen this email and
2529        * policy couldn't possibly be TOFU_POLICY_NONE.  */
2530       log_assert (policy == TOFU_POLICY_NONE);
2531
2532       if (DBG_TRUST)
2533         log_debug ("TOFU: New binding <key: %s, user id: %s>, no conflict.\n",
2534                    fingerprint, email);
2535
2536       effective_policy = TOFU_POLICY_AUTO;
2537       goto out;
2538     }
2539
2540   if (conflict_set_count == 1
2541       && (conflict_set->flags & BINDING_CONFLICT))
2542     {
2543       /* No known conflicts now, but there was a conflict.  This means
2544        * at some point, there was a conflict and we changed this
2545        * binding's policy to ask and set the conflicting key.  The
2546        * conflict can go away if there is not a cross sig between the
2547        * two keys.  In this case, just silently clear the conflict and
2548        * reset the policy to auto.  */
2549
2550       if (DBG_TRUST)
2551         log_debug ("TOFU: binding <key: %s, user id: %s> had a conflict, but it's been resolved (probably via  cross sig).\n",
2552                    fingerprint, email);
2553
2554       effective_policy = TOFU_POLICY_AUTO;
2555       conflict = NULL;
2556
2557       goto out;
2558     }
2559
2560   if (conflict_set_count == 1)
2561     {
2562       /* No conflicts and never marked as conflicting.  */
2563
2564       log_assert (!conflict);
2565
2566       effective_policy = TOFU_POLICY_AUTO;
2567
2568       goto out;
2569     }
2570
2571   /* There is a conflicting key.  */
2572   log_assert (conflict_set_count > 1);
2573   effective_policy = TOFU_POLICY_ASK;
2574   conflict = xstrdup (conflict_set->next->d);
2575
2576  out:
2577   log_assert (policy == _tofu_GET_POLICY_ERROR
2578               || policy == TOFU_POLICY_NONE
2579               || policy == TOFU_POLICY_AUTO
2580               || policy == TOFU_POLICY_GOOD
2581               || policy == TOFU_POLICY_UNKNOWN
2582               || policy == TOFU_POLICY_BAD
2583               || policy == TOFU_POLICY_ASK);
2584   /* Everything but NONE.  */
2585   log_assert (effective_policy == _tofu_GET_POLICY_ERROR
2586               || effective_policy == TOFU_POLICY_AUTO
2587               || effective_policy == TOFU_POLICY_GOOD
2588               || effective_policy == TOFU_POLICY_UNKNOWN
2589               || effective_policy == TOFU_POLICY_BAD
2590               || effective_policy == TOFU_POLICY_ASK);
2591
2592   if (effective_policy != TOFU_POLICY_ASK && conflict)
2593     conflict = NULL;
2594
2595   /* If we don't have a record of this binding, its effective policy
2596    * changed, or conflict changed, update the DB.  */
2597   if (effective_policy != _tofu_GET_POLICY_ERROR
2598       && (/* New binding.  */
2599           policy == TOFU_POLICY_NONE
2600           /* effective_policy changed.  */
2601           || effective_policy != effective_policy_orig
2602           /* conflict changed.  */
2603           || (conflict != conflict_orig
2604               && (!conflict || !conflict_orig
2605                   || strcmp (conflict, conflict_orig) != 0))))
2606     {
2607       if (record_binding (dbs, fingerprint, email, user_id,
2608                           policy == TOFU_POLICY_NONE ? TOFU_POLICY_AUTO : policy,
2609                           effective_policy, conflict, 1, 0, now) != 0)
2610         log_error (_("error setting TOFU binding's policy"
2611                      " to %s\n"), tofu_policy_str (policy));
2612     }
2613
2614   /* If the caller wants the set of conflicts, return it.  */
2615   if (effective_policy == TOFU_POLICY_ASK && conflict_setp)
2616     {
2617       if (! conflict_set)
2618         conflict_set = build_conflict_set (dbs, pk, fingerprint, email);
2619       *conflict_setp = conflict_set;
2620     }
2621   else
2622     {
2623       free_strlist (conflict_set);
2624
2625       if (conflict_setp)
2626         *conflict_setp = NULL;
2627     }
2628
2629   xfree (conflict_orig);
2630   if (conflict != conflict_orig)
2631     xfree (conflict);
2632   free_strlist (results);
2633
2634   return effective_policy;
2635 }
2636
2637
2638 /* Return the trust level (TRUST_NEVER, etc.) for the binding
2639  * <FINGERPRINT, EMAIL> (email is already normalized).  If no policy
2640  * is registered, returns TOFU_POLICY_NONE.  If an error occurs,
2641  * returns _tofu_GET_TRUST_ERROR.
2642  *
2643  * PK is the public key object for FINGERPRINT.
2644  *
2645  * USER_ID is the unadulterated user id.
2646  *
2647  * If MAY_ASK is set, then we may interact with the user.  This is
2648  * necessary if there is a conflict or the binding's policy is
2649  * TOFU_POLICY_ASK.  In the case of a conflict, we set the new
2650  * conflicting binding's policy to TOFU_POLICY_ASK.  In either case,
2651  * we return TRUST_UNDEFINED.  Note: if MAY_ASK is set, then this
2652  * function must not be called while in a transaction!  */
2653 static enum tofu_policy
2654 get_trust (ctrl_t ctrl, PKT_public_key *pk,
2655            const char *fingerprint, const char *email,
2656            const char *user_id, int may_ask,
2657            enum tofu_policy *policyp, strlist_t *conflict_setp,
2658            time_t now)
2659 {
2660   tofu_dbs_t dbs = ctrl->tofu.dbs;
2661   int in_transaction = 0;
2662   enum tofu_policy policy;
2663   int rc;
2664   char *sqerr = NULL;
2665   strlist_t conflict_set = NULL;
2666   int trust_level = TRUST_UNKNOWN;
2667   strlist_t iter;
2668
2669   log_assert (dbs);
2670
2671   if (may_ask)
2672     log_assert (dbs->in_transaction == 0);
2673
2674   if (opt.batch)
2675     may_ask = 0;
2676
2677   log_assert (pk_is_primary (pk));
2678
2679   /* Make sure _tofu_GET_TRUST_ERROR isn't equal to any of the trust
2680      levels.  */
2681   log_assert (_tofu_GET_TRUST_ERROR != TRUST_UNKNOWN
2682               && _tofu_GET_TRUST_ERROR != TRUST_EXPIRED
2683               && _tofu_GET_TRUST_ERROR != TRUST_UNDEFINED
2684               && _tofu_GET_TRUST_ERROR != TRUST_NEVER
2685               && _tofu_GET_TRUST_ERROR != TRUST_MARGINAL
2686               && _tofu_GET_TRUST_ERROR != TRUST_FULLY
2687               && _tofu_GET_TRUST_ERROR != TRUST_ULTIMATE);
2688
2689   begin_transaction (ctrl, 0);
2690   in_transaction = 1;
2691
2692   /* We need to call get_policy even if the key is ultimately trusted
2693    * to make sure the binding has been registered.  */
2694   policy = get_policy (dbs, pk, fingerprint, user_id, email,
2695                        &conflict_set, now);
2696
2697   if (policy == TOFU_POLICY_ASK)
2698     /* The conflict set should always contain at least one element:
2699      * the current key.  */
2700     log_assert (conflict_set);
2701   else
2702     /* If the policy is not TOFU_POLICY_ASK, then conflict_set will be
2703      * NULL.  */
2704     log_assert (! conflict_set);
2705
2706   /* If the key is ultimately trusted, there is nothing to do.  */
2707   {
2708     u32 kid[2];
2709
2710     keyid_from_pk (pk, kid);
2711     if (tdb_keyid_is_utk (kid))
2712       {
2713         trust_level = TRUST_ULTIMATE;
2714         policy = TOFU_POLICY_GOOD;
2715         goto out;
2716       }
2717   }
2718
2719   if (policy == TOFU_POLICY_AUTO)
2720     {
2721       policy = opt.tofu_default_policy;
2722       if (DBG_TRUST)
2723         log_debug ("TOFU: binding <key: %s, user id: %s>'s policy is"
2724                    " auto (default: %s).\n",
2725                    fingerprint, email,
2726                    tofu_policy_str (opt.tofu_default_policy));
2727
2728       if (policy == TOFU_POLICY_ASK)
2729         /* The default policy is ASK, but there is no conflict (policy
2730          * was 'auto').  In this case, we need to make sure the
2731          * conflict set includes at least the current user id.  */
2732         {
2733           add_to_strlist (&conflict_set, fingerprint);
2734         }
2735     }
2736   switch (policy)
2737     {
2738     case TOFU_POLICY_AUTO:
2739     case TOFU_POLICY_GOOD:
2740     case TOFU_POLICY_UNKNOWN:
2741     case TOFU_POLICY_BAD:
2742       /* The saved judgement is auto -> auto, good, unknown or bad.
2743        * We don't need to ask the user anything.  */
2744       if (DBG_TRUST)
2745         log_debug ("TOFU: Known binding <key: %s, user id: %s>'s policy: %s\n",
2746                    fingerprint, email, tofu_policy_str (policy));
2747       trust_level = tofu_policy_to_trust_level (policy);
2748       goto out;
2749
2750     case TOFU_POLICY_ASK:
2751       /* We need to ask the user what to do.  */
2752       break;
2753
2754     case _tofu_GET_POLICY_ERROR:
2755       trust_level = _tofu_GET_TRUST_ERROR;
2756       goto out;
2757
2758     default:
2759       log_bug ("%s: Impossible value for policy (%d)\n", __func__, policy);
2760     }
2761
2762
2763   /* We get here if:
2764    *
2765    *   1. The saved policy is auto and the default policy is ask
2766    *      (get_policy() == TOFU_POLICY_AUTO
2767    *       && opt.tofu_default_policy == TOFU_POLICY_ASK)
2768    *
2769    *   2. The saved policy is ask (either last time the user selected
2770    *      accept once or reject once or there was a conflict and this
2771    *      binding's policy was changed from auto to ask)
2772    *      (policy == TOFU_POLICY_ASK).
2773    */
2774   log_assert (policy == TOFU_POLICY_ASK);
2775
2776   if (may_ask)
2777     {
2778       /* We can't be in a normal transaction in ask_about_binding.  */
2779       end_transaction (ctrl, 0);
2780       in_transaction = 0;
2781
2782       /* If we get here, we need to ask the user about the binding.  */
2783       ask_about_binding (ctrl,
2784                          &policy,
2785                          &trust_level,
2786                          conflict_set,
2787                          fingerprint,
2788                          email,
2789                          user_id,
2790                          now);
2791     }
2792   else
2793     {
2794       trust_level = TRUST_UNDEFINED;
2795     }
2796
2797   /* Mark any conflicting bindings that have an automatic policy as
2798    * now requiring confirmation.  Note: we do this after we ask for
2799    * confirmation so that when the current policy is printed, it is
2800    * correct.  */
2801   if (! in_transaction)
2802     {
2803       begin_transaction (ctrl, 0);
2804       in_transaction = 1;
2805     }
2806
2807   /* The conflict set should always contain at least one element:
2808    * the current key.  */
2809   log_assert (conflict_set);
2810
2811   for (iter = conflict_set->next; iter; iter = iter->next)
2812     {
2813       /* We don't immediately set the effective policy to 'ask,
2814          because  */
2815       rc = gpgsql_exec_printf
2816         (dbs->db, NULL, NULL, &sqerr,
2817          "update bindings set effective_policy = %d, conflict = %Q"
2818          " where email = %Q and fingerprint = %Q and effective_policy != %d;",
2819          TOFU_POLICY_NONE, fingerprint,
2820          email, iter->d, TOFU_POLICY_ASK);
2821       if (rc)
2822         {
2823           log_error (_("error changing TOFU policy: %s\n"), sqerr);
2824           print_further_info ("binding: <key: %s, user id: %s>",
2825                               fingerprint, user_id);
2826           sqlite3_free (sqerr);
2827           sqerr = NULL;
2828           rc = gpg_error (GPG_ERR_GENERAL);
2829         }
2830       else if (DBG_TRUST)
2831         log_debug ("Set %s to conflict with %s\n",
2832                    iter->d, fingerprint);
2833     }
2834
2835  out:
2836   if (in_transaction)
2837     end_transaction (ctrl, 0);
2838
2839   if (policyp)
2840     *policyp = policy;
2841
2842   if (conflict_setp)
2843     *conflict_setp = conflict_set;
2844   else
2845     free_strlist (conflict_set);
2846
2847   return trust_level;
2848 }
2849
2850
2851 /* Return a malloced string of the form
2852  *    "7~months"
2853  * The caller should replace all '~' in the returned string by a space
2854  * and also free the returned string.
2855  *
2856  * This is actually a bad hack which may not work correctly with all
2857  * languages.
2858  */
2859 static char *
2860 time_ago_str (long long int t)
2861 {
2862   /* It would be nice to use a macro to do this, but gettext
2863      works on the unpreprocessed code.  */
2864 #define MIN_SECS (60)
2865 #define HOUR_SECS (60 * MIN_SECS)
2866 #define DAY_SECS (24 * HOUR_SECS)
2867 #define WEEK_SECS (7 * DAY_SECS)
2868 #define MONTH_SECS (30 * DAY_SECS)
2869 #define YEAR_SECS (365 * DAY_SECS)
2870
2871   if (t > 2 * YEAR_SECS)
2872     {
2873       long long int c = t / YEAR_SECS;
2874       return xtryasprintf (ngettext("%lld~year", "%lld~years", c), c);
2875     }
2876   if (t > 2 * MONTH_SECS)
2877     {
2878       long long int c = t / MONTH_SECS;
2879       return xtryasprintf (ngettext("%lld~month", "%lld~months", c), c);
2880     }
2881   if (t > 2 * WEEK_SECS)
2882     {
2883       long long int c = t / WEEK_SECS;
2884       return xtryasprintf (ngettext("%lld~week", "%lld~weeks", c), c);
2885     }
2886   if (t > 2 * DAY_SECS)
2887     {
2888       long long int c = t / DAY_SECS;
2889       return xtryasprintf (ngettext("%lld~day", "%lld~days", c), c);
2890     }
2891   if (t > 2 * HOUR_SECS)
2892     {
2893       long long int c = t / HOUR_SECS;
2894       return xtryasprintf (ngettext("%lld~hour", "%lld~hours", c), c);
2895     }
2896   if (t > 2 * MIN_SECS)
2897     {
2898       long long int c = t / MIN_SECS;
2899       return xtryasprintf (ngettext("%lld~minute", "%lld~minutes", c), c);
2900     }
2901   return xtryasprintf (ngettext("%lld~second", "%lld~seconds", t), t);
2902 }
2903
2904
2905 /* If FP is NULL, write TOFU_STATS status line.  If FP is not NULL
2906  * write a "tfs" record to that stream. */
2907 static void
2908 write_stats_status (estream_t fp,
2909                     enum tofu_policy policy,
2910                     unsigned long signature_count,
2911                     unsigned long signature_first_seen,
2912                     unsigned long signature_most_recent,
2913                     unsigned long signature_days,
2914                     unsigned long encryption_count,
2915                     unsigned long encryption_first_done,
2916                     unsigned long encryption_most_recent,
2917                     unsigned long encryption_days)
2918 {
2919   int summary;
2920   int validity;
2921   unsigned long days;
2922
2923   /* Use the euclidean distance (m = sqrt(a^2 + b^2)) rather then the
2924      sum of the magnitudes (m = a + b) to ensure a balance between
2925      verified signatures and encrypted messages.  */
2926   days = sqrtu32 (signature_days * signature_days
2927                   + encryption_days * encryption_days);
2928
2929   if (days < 1)
2930     validity = 1; /* Key without history.  */
2931   else if (days < 2 * BASIC_TRUST_THRESHOLD)
2932     validity = 2; /* Key with too little history.  */
2933   else if (days < 2 * FULL_TRUST_THRESHOLD)
2934     validity = 3; /* Key with enough history for basic trust.  */
2935   else
2936     validity = 4; /* Key with a lot of history.  */
2937
2938   if (policy == TOFU_POLICY_ASK)
2939     summary = 0; /* Key requires attention.  */
2940   else
2941     summary = validity;
2942
2943   if (fp)
2944     {
2945       es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:%lu:%lu:\n",
2946                   summary, signature_count, encryption_count,
2947                   tofu_policy_str (policy),
2948                   signature_first_seen, signature_most_recent,
2949                   encryption_first_done, encryption_most_recent,
2950                   validity, signature_days, encryption_days);
2951     }
2952   else
2953     {
2954       write_status_printf (STATUS_TOFU_STATS,
2955                            "%d %lu %lu %s %lu %lu %lu %lu %d %lu %lu",
2956                            summary,
2957                            signature_count,
2958                            encryption_count,
2959                            tofu_policy_str (policy),
2960                            signature_first_seen,
2961                            signature_most_recent,
2962                            encryption_first_done,
2963                            encryption_most_recent,
2964                            validity,
2965                            signature_days, encryption_days);
2966     }
2967 }
2968
2969 /* Note: If OUTFP is not NULL, this function merely prints a "tfs" record
2970  * to OUTFP.
2971  *
2972  * POLICY is the key's policy (as returned by get_policy).
2973  *
2974  * Returns 0 if if ONLY_STATUS_FD is set.  Otherwise, returns whether
2975  * the caller should call show_warning after iterating over all user
2976  * ids.
2977  */
2978 static int
2979 show_statistics (tofu_dbs_t dbs,
2980                  const char *fingerprint, const char *email,
2981                  enum tofu_policy policy,
2982                  estream_t outfp, int only_status_fd, time_t now)
2983 {
2984   char *fingerprint_pp;
2985   int rc;
2986   strlist_t strlist = NULL;
2987   char *err = NULL;
2988
2989   unsigned long signature_first_seen = 0;
2990   unsigned long signature_most_recent = 0;
2991   unsigned long signature_count = 0;
2992   unsigned long signature_days = 0;
2993   unsigned long encryption_first_done = 0;
2994   unsigned long encryption_most_recent = 0;
2995   unsigned long encryption_count = 0;
2996   unsigned long encryption_days = 0;
2997
2998   int show_warning = 0;
2999
3000   if (only_status_fd && ! is_status_enabled ())
3001     return 0;
3002
3003   fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
3004
3005   /* Get the signature stats.  */
3006   rc = gpgsql_exec_printf
3007     (dbs->db, strings_collect_cb, &strlist, &err,
3008      "select count (*), coalesce (min (signatures.time), 0),\n"
3009      "  coalesce (max (signatures.time), 0)\n"
3010      " from signatures\n"
3011      " left join bindings on signatures.binding = bindings.oid\n"
3012      " where fingerprint = %Q and email = %Q;",
3013      fingerprint, email);
3014   if (rc)
3015     {
3016       log_error (_("error reading TOFU database: %s\n"), err);
3017       print_further_info ("getting signature statistics");
3018       sqlite3_free (err);
3019       rc = gpg_error (GPG_ERR_GENERAL);
3020       goto out;
3021     }
3022   rc = gpgsql_exec_printf
3023     (dbs->db, strings_collect_cb, &strlist, &err,
3024      "select count (*) from\n"
3025      "  (select round(signatures.time / (24 * 60 * 60)) day\n"
3026      "    from signatures\n"
3027      "    left join bindings on signatures.binding = bindings.oid\n"
3028      "    where fingerprint = %Q and email = %Q\n"
3029      "    group by day);",
3030      fingerprint, email);
3031   if (rc)
3032     {
3033       log_error (_("error reading TOFU database: %s\n"), err);
3034       print_further_info ("getting signature statistics (by day)");
3035       sqlite3_free (err);
3036       rc = gpg_error (GPG_ERR_GENERAL);
3037       goto out;
3038     }
3039
3040   if (strlist)
3041     {
3042       /* We expect exactly 4 elements.  */
3043       log_assert (strlist->next);
3044       log_assert (strlist->next->next);
3045       log_assert (strlist->next->next->next);
3046       log_assert (! strlist->next->next->next->next);
3047
3048       string_to_ulong (&signature_days, strlist->d, -1, __LINE__);
3049       string_to_ulong (&signature_count, strlist->next->d, -1, __LINE__);
3050       string_to_ulong (&signature_first_seen,
3051                        strlist->next->next->d, -1, __LINE__);
3052       string_to_ulong (&signature_most_recent,
3053                        strlist->next->next->next->d, -1, __LINE__);
3054
3055       free_strlist (strlist);
3056       strlist = NULL;
3057     }
3058
3059   /* Get the encryption stats.  */
3060   rc = gpgsql_exec_printf
3061     (dbs->db, strings_collect_cb, &strlist, &err,
3062      "select count (*), coalesce (min (encryptions.time), 0),\n"
3063      "  coalesce (max (encryptions.time), 0)\n"
3064      " from encryptions\n"
3065      " left join bindings on encryptions.binding = bindings.oid\n"
3066      " where fingerprint = %Q and email = %Q;",
3067      fingerprint, email);
3068   if (rc)
3069     {
3070       log_error (_("error reading TOFU database: %s\n"), err);
3071       print_further_info ("getting encryption statistics");
3072       sqlite3_free (err);
3073       rc = gpg_error (GPG_ERR_GENERAL);
3074       goto out;
3075     }
3076   rc = gpgsql_exec_printf
3077     (dbs->db, strings_collect_cb, &strlist, &err,
3078      "select count (*) from\n"
3079      "  (select round(encryptions.time / (24 * 60 * 60)) day\n"
3080      "    from encryptions\n"
3081      "    left join bindings on encryptions.binding = bindings.oid\n"
3082      "    where fingerprint = %Q and email = %Q\n"
3083      "    group by day);",
3084      fingerprint, email);
3085   if (rc)
3086     {
3087       log_error (_("error reading TOFU database: %s\n"), err);
3088       print_further_info ("getting encryption statistics (by day)");
3089       sqlite3_free (err);
3090       rc = gpg_error (GPG_ERR_GENERAL);
3091       goto out;
3092     }
3093
3094   if (strlist)
3095     {
3096       /* We expect exactly 4 elements.  */
3097       log_assert (strlist->next);
3098       log_assert (strlist->next->next);
3099       log_assert (strlist->next->next->next);
3100       log_assert (! strlist->next->next->next->next);
3101
3102       string_to_ulong (&encryption_days, strlist->d, -1, __LINE__);
3103       string_to_ulong (&encryption_count, strlist->next->d, -1, __LINE__);
3104       string_to_ulong (&encryption_first_done,
3105                        strlist->next->next->d, -1, __LINE__);
3106       string_to_ulong (&encryption_most_recent,
3107                        strlist->next->next->next->d, -1, __LINE__);
3108
3109       free_strlist (strlist);
3110       strlist = NULL;
3111     }
3112
3113   if (!outfp)
3114     write_status_text_and_buffer (STATUS_TOFU_USER, fingerprint,
3115                                   email, strlen (email), 0);
3116
3117   write_stats_status (outfp, policy,
3118                       signature_count,
3119                       signature_first_seen,
3120                       signature_most_recent,
3121                       signature_days,
3122                       encryption_count,
3123                       encryption_first_done,
3124                       encryption_most_recent,
3125                       encryption_days);
3126
3127   if (!outfp && !only_status_fd)
3128     {
3129       estream_t fp;
3130       char *msg;
3131
3132       fp = es_fopenmem (0, "rw,samethread");
3133       if (! fp)
3134         log_fatal ("error creating memory stream: %s\n",
3135                    gpg_strerror (gpg_error_from_syserror()));
3136
3137       if (signature_count == 0 && encryption_count == 0)
3138         {
3139           es_fprintf (fp,
3140                       _("%s: Verified 0~signatures and encrypted 0~messages."),
3141                       email);
3142         }
3143       else
3144         {
3145           if (signature_count == 0)
3146             es_fprintf (fp, _("%s: Verified 0 signatures."), email);
3147           else
3148             {
3149               /* TRANSLATORS: The final %s is replaced by a string like
3150                  "7~months". */
3151               char *ago_str = time_ago_str (now - signature_first_seen);
3152               es_fprintf
3153                 (fp,
3154                  ngettext("%s: Verified %ld~signature in the past %s.",
3155                           "%s: Verified %ld~signatures in the past %s.",
3156                           signature_count),
3157                  email, signature_count, ago_str);
3158               xfree (ago_str);
3159             }
3160
3161           es_fputs ("  ", fp);
3162
3163           if (encryption_count == 0)
3164             es_fprintf (fp, _("Encrypted 0 messages."));
3165           else
3166             {
3167               char *ago_str = time_ago_str (now - encryption_first_done);
3168
3169               /* TRANSLATORS: The final %s is replaced by a string like
3170                  "7~months". */
3171               es_fprintf (fp,
3172                           ngettext("Encrypted %ld~message in the past %s.",
3173                                    "Encrypted %ld~messages in the past %s.",
3174                                    encryption_count),
3175                           encryption_count, ago_str);
3176               xfree (ago_str);
3177             }
3178         }
3179
3180       if (opt.verbose)
3181         {
3182           es_fputs ("  ", fp);
3183           es_fprintf (fp, _("(policy: %s)"), tofu_policy_str (policy));
3184         }
3185       es_fputs ("\n", fp);
3186
3187
3188       {
3189         char *tmpmsg, *p;
3190         es_fputc (0, fp);
3191         if (es_fclose_snatch (fp, (void **) &tmpmsg, NULL))
3192           log_fatal ("error snatching memory stream\n");
3193         msg = format_text (tmpmsg, 0, 72, 80);
3194         es_free (tmpmsg);
3195
3196         /* Print a status line but suppress the trailing LF.
3197          * Spaces are not percent escaped. */
3198         if (*msg)
3199           write_status_buffer (STATUS_TOFU_STATS_LONG,
3200                                msg, strlen (msg)-1, -1);
3201
3202         /* Remove the non-breaking space markers.  */
3203         for (p=msg; *p; p++)
3204           if (*p == '~')
3205             *p = ' ';
3206       }
3207
3208       log_string (GPGRT_LOG_INFO, msg);
3209       xfree (msg);
3210
3211       if (policy == TOFU_POLICY_AUTO)
3212         {
3213           if (signature_count == 0)
3214             log_info (_("Warning: we have yet to see"
3215                         " a message signed using this key and user id!\n"));
3216           else if (signature_count == 1)
3217             log_info (_("Warning: we've only seen one message"
3218                         " signed using this key and user id!\n"));
3219
3220           if (encryption_count == 0)
3221             log_info (_("Warning: you have yet to encrypt"
3222                         " a message to this key!\n"));
3223           else if (encryption_count == 1)
3224             log_info (_("Warning: you have only encrypted"
3225                         " one message to this key!\n"));
3226
3227           /* Cf. write_stats_status  */
3228           if (sqrtu32 (encryption_count * encryption_count
3229                        + signature_count * signature_count)
3230               < 2 * BASIC_TRUST_THRESHOLD)
3231             show_warning = 1;
3232         }
3233     }
3234
3235  out:
3236   xfree (fingerprint_pp);
3237
3238   return show_warning;
3239 }
3240
3241 static void
3242 show_warning (const char *fingerprint, strlist_t user_id_list)
3243 {
3244   char *set_policy_command;
3245   char *text;
3246   char *tmpmsg;
3247
3248   set_policy_command =
3249     xasprintf ("gpg --tofu-policy bad %s", fingerprint);
3250
3251   tmpmsg = xasprintf
3252     (ngettext
3253      ("Warning: if you think you've seen more signatures "
3254       "by this key and user id, then this key might be a "
3255       "forgery!  Carefully examine the email address for small "
3256       "variations.  If the key is suspect, then use\n"
3257       "  %s\n"
3258       "to mark it as being bad.\n",
3259       "Warning: if you think you've seen more signatures "
3260       "by this key and these user ids, then this key might be a "
3261       "forgery!  Carefully examine the email addresses for small "
3262       "variations.  If the key is suspect, then use\n"
3263       "  %s\n"
3264       "to mark it as being bad.\n",
3265       strlist_length (user_id_list)),
3266      set_policy_command);
3267
3268   text = format_text (tmpmsg, 0, 72, 80);
3269   xfree (tmpmsg);
3270   log_string (GPGRT_LOG_INFO, text);
3271   xfree (text);
3272
3273   es_free (set_policy_command);
3274 }
3275
3276
3277 /* Extract the email address from a user id and normalize it.  If the
3278    user id doesn't contain an email address, then we use the whole
3279    user_id and normalize that.  The returned string must be freed.  */
3280 static char *
3281 email_from_user_id (const char *user_id)
3282 {
3283   char *email = mailbox_from_userid (user_id);
3284   if (! email)
3285     {
3286       /* Hmm, no email address was provided or we are out of core.  Just
3287          take the lower-case version of the whole user id.  It could be
3288          a hostname, for instance.  */
3289       email = ascii_strlwr (xstrdup (user_id));
3290     }
3291
3292   return email;
3293 }
3294
3295 /* Register the signature with the bindings <fingerprint, USER_ID>,
3296    for each USER_ID in USER_ID_LIST.  The fingerprint is taken from
3297    the primary key packet PK.
3298
3299    SIG_DIGEST_BIN is the binary representation of the message's
3300    digest.  SIG_DIGEST_BIN_LEN is its length.
3301
3302    SIG_TIME is the time that the signature was generated.
3303
3304    ORIGIN is a free-formed string describing the origin of the
3305    signature.  If this was from an email and the Claws MUA was used,
3306    then this should be something like: "email:claws".  If this is
3307    NULL, the default is simply "unknown".
3308
3309    If MAY_ASK is 1, then this function may interact with the user.
3310    This is necessary if there is a conflict or the binding's policy is
3311    TOFU_POLICY_ASK.
3312
3313    This function returns 0 on success and an error code if an error
3314    occurred.  */
3315 gpg_error_t
3316 tofu_register_signature (ctrl_t ctrl,
3317                          PKT_public_key *pk, strlist_t user_id_list,
3318                          const byte *sig_digest_bin, int sig_digest_bin_len,
3319                          time_t sig_time, const char *origin)
3320 {
3321   time_t now = gnupg_get_time ();
3322   gpg_error_t rc;
3323   tofu_dbs_t dbs;
3324   char *fingerprint = NULL;
3325   strlist_t user_id;
3326   char *email = NULL;
3327   char *err = NULL;
3328   char *sig_digest;
3329   unsigned long c;
3330
3331   dbs = opendbs (ctrl);
3332   if (! dbs)
3333     {
3334       rc = gpg_error (GPG_ERR_GENERAL);
3335       log_error (_("error opening TOFU database: %s\n"),
3336                  gpg_strerror (rc));
3337       return rc;
3338     }
3339
3340   /* We do a query and then an insert.  Make sure they are atomic
3341      by wrapping them in a transaction.  */
3342   rc = begin_transaction (ctrl, 0);
3343   if (rc)
3344     return rc;
3345
3346   log_assert (pk_is_primary (pk));
3347
3348   sig_digest = make_radix64_string (sig_digest_bin, sig_digest_bin_len);
3349   fingerprint = hexfingerprint (pk, NULL, 0);
3350
3351   if (! origin)
3352     /* The default origin is simply "unknown".  */
3353     origin = "unknown";
3354
3355   for (user_id = user_id_list; user_id; user_id = user_id->next)
3356     {
3357       email = email_from_user_id (user_id->d);
3358
3359       if (DBG_TRUST)
3360         log_debug ("TOFU: Registering signature %s with binding"
3361                    " <key: %s, user id: %s>\n",
3362                    sig_digest, fingerprint, email);
3363
3364       /* Make sure the binding exists and record any TOFU
3365          conflicts.  */
3366       if (get_trust (ctrl, pk, fingerprint, email, user_id->d,
3367                      0, NULL, NULL, now)
3368           == _tofu_GET_TRUST_ERROR)
3369         {
3370           rc = gpg_error (GPG_ERR_GENERAL);
3371           xfree (email);
3372           break;
3373         }
3374
3375       /* If we've already seen this signature before, then don't add
3376          it again.  */
3377       rc = gpgsql_stepx
3378         (dbs->db, &dbs->s.register_already_seen,
3379          get_single_unsigned_long_cb2, &c, &err,
3380          "select count (*)\n"
3381          " from signatures left join bindings\n"
3382          "  on signatures.binding = bindings.oid\n"
3383          " where fingerprint = ? and email = ? and sig_time = ?\n"
3384          "  and sig_digest = ?",
3385          GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3386          GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3387          GPGSQL_ARG_STRING, sig_digest,
3388          GPGSQL_ARG_END);
3389       if (rc)
3390         {
3391           log_error (_("error reading TOFU database: %s\n"), err);
3392           print_further_info ("checking existence");
3393           sqlite3_free (err);
3394           rc = gpg_error (GPG_ERR_GENERAL);
3395         }
3396       else if (c > 1)
3397         /* Duplicates!  This should not happen.  In particular,
3398            because <fingerprint, email, sig_time, sig_digest> is the
3399            primary key!  */
3400         log_debug ("SIGNATURES DB contains duplicate records"
3401                    " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3402                    " origin: %s>."
3403                    "  Please report.\n",
3404                    fingerprint, email, (unsigned long) sig_time,
3405                    sig_digest, origin);
3406       else if (c == 1)
3407         {
3408           if (DBG_TRUST)
3409             log_debug ("Already observed the signature and binding"
3410                        " <key: %s, email: %s, time: 0x%lx, sig: %s,"
3411                        " origin: %s>\n",
3412                        fingerprint, email, (unsigned long) sig_time,
3413                        sig_digest, origin);
3414         }
3415       else if (opt.dry_run)
3416         {
3417           log_info ("TOFU database update skipped due to --dry-run\n");
3418         }
3419       else
3420         /* This is the first time that we've seen this signature and
3421            binding.  Record it.  */
3422         {
3423           if (DBG_TRUST)
3424             log_debug ("TOFU: Saving signature"
3425                        " <key: %s, user id: %s, sig: %s>\n",
3426                        fingerprint, email, sig_digest);
3427
3428           log_assert (c == 0);
3429
3430           rc = gpgsql_stepx
3431             (dbs->db, &dbs->s.register_signature, NULL, NULL, &err,
3432              "insert into signatures\n"
3433              " (binding, sig_digest, origin, sig_time, time)\n"
3434              " values\n"
3435              " ((select oid from bindings\n"
3436              "    where fingerprint = ? and email = ?),\n"
3437              "  ?, ?, ?, ?);",
3438              GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3439              GPGSQL_ARG_STRING, sig_digest, GPGSQL_ARG_STRING, origin,
3440              GPGSQL_ARG_LONG_LONG, (long long) sig_time,
3441              GPGSQL_ARG_LONG_LONG, (long long) now,
3442              GPGSQL_ARG_END);
3443           if (rc)
3444             {
3445               log_error (_("error updating TOFU database: %s\n"), err);
3446               print_further_info ("insert signatures");
3447               sqlite3_free (err);
3448               rc = gpg_error (GPG_ERR_GENERAL);
3449             }
3450         }
3451
3452       xfree (email);
3453
3454       if (rc)
3455         break;
3456     }
3457
3458   if (rc)
3459     rollback_transaction (ctrl);
3460   else
3461     rc = end_transaction (ctrl, 0);
3462
3463   xfree (fingerprint);
3464   xfree (sig_digest);
3465
3466   return rc;
3467 }
3468
3469 gpg_error_t
3470 tofu_register_encryption (ctrl_t ctrl,
3471                           PKT_public_key *pk, strlist_t user_id_list,
3472                           int may_ask)
3473 {
3474   time_t now = gnupg_get_time ();
3475   gpg_error_t rc = 0;
3476   tofu_dbs_t dbs;
3477   kbnode_t kb = NULL;
3478   int free_user_id_list = 0;
3479   char *fingerprint = NULL;
3480   strlist_t user_id;
3481   char *err = NULL;
3482
3483   dbs = opendbs (ctrl);
3484   if (! dbs)
3485     {
3486       rc = gpg_error (GPG_ERR_GENERAL);
3487       log_error (_("error opening TOFU database: %s\n"),
3488                  gpg_strerror (rc));
3489       return rc;
3490     }
3491
3492   if (/* We need the key block to find the primary key.  */
3493       ! pk_is_primary (pk)
3494       /* We need the key block to find all user ids.  */
3495       || ! user_id_list)
3496     kb = get_pubkeyblock (pk->keyid);
3497
3498   /* Make sure PK is a primary key.  */
3499   if (! pk_is_primary (pk))
3500     pk = kb->pkt->pkt.public_key;
3501
3502   if (! user_id_list)
3503     {
3504       /* Use all non-revoked user ids.  Do use expired user ids.  */
3505       kbnode_t n = kb;
3506
3507       while ((n = find_next_kbnode (n, PKT_USER_ID)))
3508         {
3509           PKT_user_id *uid = n->pkt->pkt.user_id;
3510
3511           if (uid->is_revoked)
3512             continue;
3513
3514           add_to_strlist (&user_id_list, uid->name);
3515         }
3516
3517       free_user_id_list = 1;
3518
3519       if (! user_id_list)
3520         log_info (_("WARNING: Encrypting to %s, which has no "
3521                     "non-revoked user ids\n"),
3522                   keystr (pk->keyid));
3523     }
3524
3525   fingerprint = hexfingerprint (pk, NULL, 0);
3526
3527   tofu_begin_batch_update (ctrl);
3528   tofu_resume_batch_transaction (ctrl);
3529
3530   for (user_id = user_id_list; user_id; user_id = user_id->next)
3531     {
3532       char *email = email_from_user_id (user_id->d);
3533       strlist_t conflict_set = NULL;
3534       enum tofu_policy policy;
3535
3536       /* Make sure the binding exists and that we recognize any
3537          conflicts.  */
3538       int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3539                           may_ask, &policy, &conflict_set, now);
3540       if (tl == _tofu_GET_TRUST_ERROR)
3541         {
3542           /* An error.  */
3543           rc = gpg_error (GPG_ERR_GENERAL);
3544           xfree (email);
3545           goto die;
3546         }
3547
3548
3549       /* If there is a conflict and MAY_ASK is true, we need to show
3550        * the TOFU statistics for the current binding and the
3551        * conflicting bindings.  But, if we are not in batch mode, then
3552        * they have already been printed (this is required to make sure
3553        * the information is available to the caller before cpr_get is
3554        * called).  */
3555       if (policy == TOFU_POLICY_ASK && may_ask && opt.batch)
3556         {
3557           strlist_t iter;
3558
3559           /* The conflict set should contain at least the current
3560            * key.  */
3561           log_assert (conflict_set);
3562
3563           for (iter = conflict_set; iter; iter = iter->next)
3564             show_statistics (dbs, iter->d, email,
3565                              TOFU_POLICY_ASK, NULL, 1, now);
3566         }
3567
3568       free_strlist (conflict_set);
3569
3570       rc = gpgsql_stepx
3571         (dbs->db, &dbs->s.register_encryption, NULL, NULL, &err,
3572          "insert into encryptions\n"
3573          " (binding, time)\n"
3574          " values\n"
3575          " ((select oid from bindings\n"
3576          "    where fingerprint = ? and email = ?),\n"
3577          "  ?);",
3578          GPGSQL_ARG_STRING, fingerprint, GPGSQL_ARG_STRING, email,
3579          GPGSQL_ARG_LONG_LONG, (long long) now,
3580          GPGSQL_ARG_END);
3581       if (rc)
3582         {
3583           log_error (_("error updating TOFU database: %s\n"), err);
3584           print_further_info ("insert encryption");
3585           sqlite3_free (err);
3586           rc = gpg_error (GPG_ERR_GENERAL);
3587         }
3588
3589       xfree (email);
3590     }
3591
3592  die:
3593   tofu_end_batch_update (ctrl);
3594
3595   if (kb)
3596     release_kbnode (kb);
3597
3598   if (free_user_id_list)
3599     free_strlist (user_id_list);
3600
3601   xfree (fingerprint);
3602
3603   return rc;
3604 }
3605
3606
3607 /* Combine a trust level returned from the TOFU trust model with a
3608    trust level returned by the PGP trust model.  This is primarily of
3609    interest when the trust model is tofu+pgp (TM_TOFU_PGP).
3610
3611    This function ors together the upper bits (the values not covered
3612    by TRUST_MASK, i.e., TRUST_FLAG_REVOKED, etc.).  */
3613 int
3614 tofu_wot_trust_combine (int tofu_base, int wot_base)
3615 {
3616   int tofu = tofu_base & TRUST_MASK;
3617   int wot = wot_base & TRUST_MASK;
3618   int upper = (tofu_base & ~TRUST_MASK) | (wot_base & ~TRUST_MASK);
3619
3620   log_assert (tofu == TRUST_UNKNOWN
3621               || tofu == TRUST_EXPIRED
3622               || tofu == TRUST_UNDEFINED
3623               || tofu == TRUST_NEVER
3624               || tofu == TRUST_MARGINAL
3625               || tofu == TRUST_FULLY
3626               || tofu == TRUST_ULTIMATE);
3627   log_assert (wot == TRUST_UNKNOWN
3628               || wot == TRUST_EXPIRED
3629               || wot == TRUST_UNDEFINED
3630               || wot == TRUST_NEVER
3631               || wot == TRUST_MARGINAL
3632               || wot == TRUST_FULLY
3633               || wot == TRUST_ULTIMATE);
3634
3635   /* We first consider negative trust policys.  These trump positive
3636      trust policies.  */
3637   if (tofu == TRUST_NEVER || wot == TRUST_NEVER)
3638     /* TRUST_NEVER trumps everything else.  */
3639     return upper | TRUST_NEVER;
3640   if (tofu == TRUST_EXPIRED || wot == TRUST_EXPIRED)
3641     /* TRUST_EXPIRED trumps everything but TRUST_NEVER.  */
3642     return upper | TRUST_EXPIRED;
3643
3644   /* Now we only have positive or neutral trust policies.  We take
3645      the max.  */
3646   if (tofu == TRUST_ULTIMATE)
3647     return upper | TRUST_ULTIMATE | TRUST_FLAG_TOFU_BASED;
3648   if (wot == TRUST_ULTIMATE)
3649     return upper | TRUST_ULTIMATE;
3650
3651   if (tofu == TRUST_FULLY)
3652     return upper | TRUST_FULLY | TRUST_FLAG_TOFU_BASED;
3653   if (wot == TRUST_FULLY)
3654     return upper | TRUST_FULLY;
3655
3656   if (tofu == TRUST_MARGINAL)
3657     return upper | TRUST_MARGINAL | TRUST_FLAG_TOFU_BASED;
3658   if (wot == TRUST_MARGINAL)
3659     return upper | TRUST_MARGINAL;
3660
3661   if (tofu == TRUST_UNDEFINED)
3662     return upper | TRUST_UNDEFINED | TRUST_FLAG_TOFU_BASED;
3663   if (wot == TRUST_UNDEFINED)
3664     return upper | TRUST_UNDEFINED;
3665
3666   return upper | TRUST_UNKNOWN;
3667 }
3668
3669
3670 /* Write a "tfs" record for a --with-colons listing.  */
3671 gpg_error_t
3672 tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
3673                        PKT_public_key *pk, const char *user_id)
3674 {
3675   time_t now = gnupg_get_time ();
3676   gpg_error_t err;
3677   tofu_dbs_t dbs;
3678   char *fingerprint;
3679   char *email;
3680   enum tofu_policy policy;
3681
3682   if (!*user_id)
3683     return 0;  /* No TOFU stats possible for an empty ID.  */
3684
3685   dbs = opendbs (ctrl);
3686   if (!dbs)
3687     {
3688       err = gpg_error (GPG_ERR_GENERAL);
3689       log_error (_("error opening TOFU database: %s\n"), gpg_strerror (err));
3690       return err;
3691     }
3692
3693   fingerprint = hexfingerprint (pk, NULL, 0);
3694   email = email_from_user_id (user_id);
3695   policy = get_policy (dbs, pk, fingerprint, user_id, email, NULL, now);
3696
3697   show_statistics (dbs, fingerprint, email, policy, fp, 0, now);
3698
3699   xfree (email);
3700   xfree (fingerprint);
3701   return 0;
3702 }
3703
3704
3705 /* Return the validity (TRUST_NEVER, etc.) of the bindings
3706    <FINGERPRINT, USER_ID>, for each USER_ID in USER_ID_LIST.  If
3707    USER_ID_LIST->FLAG is set, then the id is considered to be expired.
3708
3709    PK is the primary key packet.
3710
3711    If MAY_ASK is 1 and the policy is TOFU_POLICY_ASK, then the user
3712    will be prompted to choose a policy.  If MAY_ASK is 0 and the
3713    policy is TOFU_POLICY_ASK, then TRUST_UNKNOWN is returned.
3714
3715    Returns TRUST_UNDEFINED if an error occurs.  */
3716 int
3717 tofu_get_validity (ctrl_t ctrl, PKT_public_key *pk, strlist_t user_id_list,
3718                    int may_ask)
3719 {
3720   time_t now = gnupg_get_time ();
3721   tofu_dbs_t dbs;
3722   char *fingerprint = NULL;
3723   strlist_t user_id;
3724   int trust_level = TRUST_UNKNOWN;
3725   int bindings = 0;
3726   int bindings_valid = 0;
3727   int need_warning = 0;
3728   int had_conflict = 0;
3729
3730   dbs = opendbs (ctrl);
3731   if (! dbs)
3732     {
3733       log_error (_("error opening TOFU database: %s\n"),
3734                  gpg_strerror (GPG_ERR_GENERAL));
3735       return TRUST_UNDEFINED;
3736     }
3737
3738   fingerprint = hexfingerprint (pk, NULL, 0);
3739
3740   tofu_begin_batch_update (ctrl);
3741   /* Start the batch transaction now.  */
3742   tofu_resume_batch_transaction (ctrl);
3743
3744   for (user_id = user_id_list; user_id; user_id = user_id->next, bindings ++)
3745     {
3746       char *email = email_from_user_id (user_id->d);
3747       strlist_t conflict_set = NULL;
3748       enum tofu_policy policy;
3749
3750       /* Always call get_trust to make sure the binding is
3751          registered.  */
3752       int tl = get_trust (ctrl, pk, fingerprint, email, user_id->d,
3753                           may_ask, &policy, &conflict_set, now);
3754       if (tl == _tofu_GET_TRUST_ERROR)
3755         {
3756           /* An error.  */
3757           trust_level = TRUST_UNDEFINED;
3758           xfree (email);
3759           goto die;
3760         }
3761
3762       if (DBG_TRUST)
3763         log_debug ("TOFU: validity for <key: %s, user id: %s>: %s%s.\n",
3764                    fingerprint, email,
3765                    trust_value_to_string (tl),
3766                    user_id->flags ? " (but expired)" : "");
3767
3768       if (user_id->flags)
3769         tl = TRUST_EXPIRED;
3770
3771       if (tl != TRUST_EXPIRED)
3772         bindings_valid ++;
3773
3774       if (may_ask && tl != TRUST_ULTIMATE && tl != TRUST_EXPIRED)
3775         {
3776           /* If policy is ask, then we already printed out the
3777            * conflict information in ask_about_binding or will do so
3778            * in a moment.  */
3779           if (policy != TOFU_POLICY_ASK)
3780             need_warning |=
3781               show_statistics (dbs, fingerprint, email, policy, NULL, 0, now);
3782
3783           /* If there is a conflict and MAY_ASK is true, we need to
3784            * show the TOFU statistics for the current binding and the
3785            * conflicting bindings.  But, if we are not in batch mode,
3786            * then they have already been printed (this is required to
3787            * make sure the information is available to the caller
3788            * before cpr_get is called).  */
3789           if (policy == TOFU_POLICY_ASK && opt.batch)
3790             {
3791               strlist_t iter;
3792
3793               /* The conflict set should contain at least the current
3794                * key.  */
3795               log_assert (conflict_set);
3796
3797               had_conflict = 1;
3798               for (iter = conflict_set; iter; iter = iter->next)
3799                 show_statistics (dbs, iter->d, email,
3800                                  TOFU_POLICY_ASK, NULL, 1, now);
3801             }
3802         }
3803
3804       free_strlist (conflict_set);
3805
3806       if (tl == TRUST_NEVER)
3807         trust_level = TRUST_NEVER;
3808       else if (tl == TRUST_EXPIRED)
3809         /* Ignore expired bindings in the trust calculation.  */
3810         ;
3811       else if (tl > trust_level)
3812         {
3813           /* The expected values: */
3814           log_assert (tl == TRUST_UNKNOWN || tl == TRUST_UNDEFINED
3815                       || tl == TRUST_MARGINAL || tl == TRUST_FULLY
3816                       || tl == TRUST_ULTIMATE);
3817
3818           /* We assume the following ordering:  */
3819           log_assert (TRUST_UNKNOWN < TRUST_UNDEFINED);
3820           log_assert (TRUST_UNDEFINED < TRUST_MARGINAL);
3821           log_assert (TRUST_MARGINAL < TRUST_FULLY);
3822           log_assert (TRUST_FULLY < TRUST_ULTIMATE);
3823
3824           trust_level = tl;
3825         }
3826
3827       xfree (email);
3828     }
3829
3830   if (need_warning && ! had_conflict)
3831     show_warning (fingerprint, user_id_list);
3832
3833  die:
3834   tofu_end_batch_update (ctrl);
3835
3836   xfree (fingerprint);
3837
3838   if (bindings_valid == 0)
3839     {
3840       if (DBG_TRUST)
3841         log_debug ("no (of %d) valid bindings."
3842                    "  Can't get TOFU validity for this set of user ids.\n",
3843                    bindings);
3844       return TRUST_NEVER;
3845     }
3846
3847   return trust_level;
3848 }
3849
3850 /* Set the policy for all non-revoked user ids in the keyblock KB to
3851    POLICY.
3852
3853    If no key is available with the specified key id, then this
3854    function returns GPG_ERR_NO_PUBKEY.
3855
3856    Returns 0 on success and an error code otherwise.  */
3857 gpg_error_t
3858 tofu_set_policy (ctrl_t ctrl, kbnode_t kb, enum tofu_policy policy)
3859 {
3860   gpg_error_t err;
3861   time_t now = gnupg_get_time ();
3862   tofu_dbs_t dbs;
3863   PKT_public_key *pk;
3864   char *fingerprint = NULL;
3865
3866   log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
3867   pk = kb->pkt->pkt.public_key;
3868
3869   dbs = opendbs (ctrl);
3870   if (! dbs)
3871     {
3872       log_error (_("error opening TOFU database: %s\n"),
3873                  gpg_strerror (GPG_ERR_GENERAL));
3874       return gpg_error (GPG_ERR_GENERAL);
3875     }
3876
3877   if (DBG_TRUST)
3878     log_debug ("Setting TOFU policy for %s to %s\n",
3879                keystr (pk->keyid), tofu_policy_str (policy));
3880   if (! pk_is_primary (pk))
3881     log_bug ("%s: Passed a subkey, but expecting a primary key.\n", __func__);
3882
3883   fingerprint = hexfingerprint (pk, NULL, 0);
3884
3885   begin_transaction (ctrl, 0);
3886
3887   for (; kb; kb = kb->next)
3888     {
3889       PKT_user_id *user_id;
3890       char *email;
3891
3892       if (kb->pkt->pkttype != PKT_USER_ID)
3893         continue;
3894
3895       user_id = kb->pkt->pkt.user_id;
3896       if (user_id->is_revoked)
3897         /* Skip revoked user ids.  (Don't skip expired user ids, the
3898            expiry can be changed.)  */
3899         continue;
3900
3901       email = email_from_user_id (user_id->name);
3902
3903       err = record_binding (dbs, fingerprint, email, user_id->name,
3904                             policy, TOFU_POLICY_NONE, NULL, 0, 1, now);
3905       if (err)
3906         {
3907           log_error (_("error setting policy for key %s, user id \"%s\": %s"),
3908                      fingerprint, email, gpg_strerror (err));
3909           xfree (email);
3910           break;
3911         }
3912
3913       xfree (email);
3914     }
3915
3916   if (err)
3917     rollback_transaction (ctrl);
3918   else
3919     end_transaction (ctrl, 0);
3920
3921   xfree (fingerprint);
3922   return err;
3923 }
3924
3925 /* Return the TOFU policy for the specified binding in *POLICY.  If no
3926    policy has been set for the binding, sets *POLICY to
3927    TOFU_POLICY_NONE.
3928
3929    PK is a primary public key and USER_ID is a user id.
3930
3931    Returns 0 on success and an error code otherwise.  */
3932 gpg_error_t
3933 tofu_get_policy (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *user_id,
3934                  enum tofu_policy *policy)
3935 {
3936   time_t now = gnupg_get_time ();
3937   tofu_dbs_t dbs;
3938   char *fingerprint;
3939   char *email;
3940
3941   /* Make sure PK is a primary key.  */
3942   log_assert (pk_is_primary (pk));
3943
3944   dbs = opendbs (ctrl);
3945   if (! dbs)
3946     {
3947       log_error (_("error opening TOFU database: %s\n"),
3948                  gpg_strerror (GPG_ERR_GENERAL));
3949       return gpg_error (GPG_ERR_GENERAL);
3950     }
3951
3952   fingerprint = hexfingerprint (pk, NULL, 0);
3953
3954   email = email_from_user_id (user_id->name);
3955
3956   *policy = get_policy (dbs, pk, fingerprint, user_id->name, email, NULL, now);
3957
3958   xfree (email);
3959   xfree (fingerprint);
3960   if (*policy == _tofu_GET_POLICY_ERROR)
3961     return gpg_error (GPG_ERR_GENERAL);
3962   return 0;
3963 }
3964
3965 gpg_error_t
3966 tofu_notice_key_changed (ctrl_t ctrl, kbnode_t kb)
3967 {
3968   tofu_dbs_t dbs;
3969   PKT_public_key *pk;
3970   char *fingerprint;
3971   char *sqlerr = NULL;
3972   int rc;
3973
3974   /* Make sure PK is a primary key.  */
3975   setup_main_keyids (kb);
3976   pk = kb->pkt->pkt.public_key;
3977   log_assert (pk_is_primary (pk));
3978
3979   dbs = opendbs (ctrl);
3980   if (! dbs)
3981     {
3982       log_error (_("error opening TOFU database: %s\n"),
3983                  gpg_strerror (GPG_ERR_GENERAL));
3984       return gpg_error (GPG_ERR_GENERAL);
3985     }
3986
3987   fingerprint = hexfingerprint (pk, NULL, 0);
3988
3989   rc = gpgsql_stepx (dbs->db, NULL, NULL, NULL, &sqlerr,
3990                      "update bindings set effective_policy = ?"
3991                      " where fingerprint = ?;",
3992                      GPGSQL_ARG_INT, (int) TOFU_POLICY_NONE,
3993                      GPGSQL_ARG_STRING, fingerprint,
3994                      GPGSQL_ARG_END);
3995   xfree (fingerprint);
3996
3997   if (rc == _tofu_GET_POLICY_ERROR)
3998     return gpg_error (GPG_ERR_GENERAL);
3999   return 0;
4000 }