gpg: Print a warning on Tor problems.
[gnupg.git] / g10 / tofu.c
index 14e4f1d..8d535fa 100644 (file)
 
 #define CONTROL_L ('L' - 'A' + 1)
 
-/* Number of signed messages required to indicate that enough history
- * is available for basic trust.  */
-#define BASIC_TRUST_THRESHOLD  10
-/* Number of signed messages required to indicate that a lot of
- * history is available.  */
-#define FULL_TRUST_THRESHOLD  100
+/* Number of days with signed / ecnrypted messages required to
+ * indicate that enough history is available for basic trust.  */
+#define BASIC_TRUST_THRESHOLD  4
+/* Number of days with signed / encrypted messages required to
+ * indicate that a lot of history is available.  */
+#define FULL_TRUST_THRESHOLD  21
 
 
 /* A struct with data pertaining to the tofu DB.  There is one such
@@ -112,8 +112,10 @@ struct tofu_dbs_s
 /* Local prototypes.  */
 static gpg_error_t end_transaction (ctrl_t ctrl, int only_batch);
 static char *email_from_user_id (const char *user_id);
-
-
+static int show_statistics (tofu_dbs_t dbs,
+                            const char *fingerprint, const char *email,
+                            enum tofu_policy policy,
+                            estream_t outfp, int only_status_fd, time_t now);
 \f
 const char *
 tofu_policy_str (enum tofu_policy policy)
@@ -410,9 +412,12 @@ string_to_long (long *r_value, const char *string, long fallback, int line)
   if (errno || !(!strcmp (tail, ".0") || !*tail))
     {
       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
-      log_debug ("%s:%d: "
-                 "strtol failed for DB returned string (tail=%.10s): %s\n",
-                 __FILE__, line, tail, gpg_strerror (err));
+      log_debug ("%s:%d: strtol failed for TOFU DB data; returned string"
+                 " (string='%.10s%s'; tail='%.10s%s'): %s\n",
+                 __FILE__, line,
+                 string, string && strlen(string) > 10 ? "..." : "",
+                 tail, tail && strlen(tail) > 10 ? "..." : "",
+                 gpg_strerror (err));
       *r_value = fallback;
     }
   else
@@ -438,9 +443,12 @@ string_to_ulong (unsigned long *r_value, const char *string,
   if (errno || !(!strcmp (tail, ".0") || !*tail))
     {
       err = errno? gpg_error_from_errno (errno) : gpg_error (GPG_ERR_BAD_DATA);
-      log_debug ("%s:%d: "
-                 "strtoul failed for DB returned string (tail=%.10s): %s\n",
-                 __FILE__, line, tail, gpg_strerror (err));
+      log_debug ("%s:%d: strtoul failed for TOFU DB data; returned string"
+                 " (string='%.10s%s'; tail='%.10s%s'): %s\n",
+                 __FILE__, line,
+                 string, string && strlen(string) > 10 ? "..." : "",
+                 tail, tail && strlen(tail) > 10 ? "..." : "",
+                 gpg_strerror (err));
       *r_value = fallback;
     }
   else
@@ -1296,21 +1304,6 @@ signature_stats_collect_cb (void *cookie, int argc, char **argv,
   return 0;
 }
 
-/* Convert from seconds to time units.
-
-   Note: T should already be a multiple of TIME_AGO_UNIT_SMALL or
-   TIME_AGO_UNIT_MEDIUM or TIME_AGO_UNIT_LARGE.  */
-signed long
-time_ago_scale (signed long t)
-{
-  if (t < TIME_AGO_UNIT_MEDIUM)
-    return t / TIME_AGO_UNIT_SMALL;
-  if (t < TIME_AGO_UNIT_LARGE)
-    return t / TIME_AGO_UNIT_MEDIUM;
-  return t / TIME_AGO_UNIT_LARGE;
-}
-
-
 /* Format the first part of a conflict message and return that as a
  * malloced string.  */
 static char *
@@ -1340,8 +1333,11 @@ format_conflict_msg_part1 (int policy, strlist_t conflict_set,
   else if (policy == TOFU_POLICY_ASK && conflict_set->next)
     {
       int conflicts = strlist_length (conflict_set);
-      es_fprintf (fp, _("The email address \"%s\" is associated with %d keys!"),
-                  email, conflicts);
+      es_fprintf
+        (fp, ngettext("The email address \"%s\" is associated with %d key!",
+                      "The email address \"%s\" is associated with %d keys!",
+                      conflicts),
+         email, conflicts);
       if (opt.verbose)
         es_fprintf (fp,
                     _("  Since this binding's policy was 'auto', it has been "
@@ -1743,6 +1739,7 @@ ask_about_binding (ctrl_t ctrl,
       char *key = NULL;
       strlist_t binding;
       int seen_in_past = 0;
+      int encrypted = 1;
 
       es_fprintf (fp, _("Statistics for keys"
                         " with the email address \"%s\":\n"),
@@ -1756,6 +1753,14 @@ ask_about_binding (ctrl_t ctrl,
                      stats_iter->count);
 #endif
 
+          if (stats_iter->time_ago > 0 && encrypted)
+            {
+              /* We've change from the encrypted stats to the verified
+               * stats.  Reset SEEN_IN_PAST.  */
+              encrypted = 0;
+              seen_in_past = 0;
+            }
+
           if (! key || strcmp (key, stats_iter->fingerprint))
             {
               int this_key;
@@ -1794,6 +1799,9 @@ ask_about_binding (ctrl_t ctrl,
               xfree (key_pp);
 
               seen_in_past = 0;
+
+              show_statistics (dbs, stats_iter->fingerprint, email,
+                               TOFU_POLICY_ASK, NULL, 1, now);
             }
 
           if (labs(stats_iter->time_ago) == 1)
@@ -1805,50 +1813,92 @@ ask_about_binding (ctrl_t ctrl,
           seen_in_past += stats_iter->count;
 
           es_fputs ("    ", fp);
-          /* TANSLATORS: This string is concatenated with one of
-           * the day/week/month strings to form one sentence.  */
-          if (stats_iter->time_ago > 0)
-            es_fprintf (fp, ngettext("Verified %d message",
-                                     "Verified %d messages",
-                                     seen_in_past), seen_in_past);
-          else
-            es_fprintf (fp, ngettext("Encrypted %d message",
-                                     "Encrypted %d messages",
-                                     seen_in_past), seen_in_past);
 
           if (!stats_iter->count)
-            es_fputs (".", fp);
+            {
+              if (stats_iter->time_ago > 0)
+                es_fprintf (fp, ngettext("Verified %d message.",
+                                         "Verified %d messages.",
+                                         seen_in_past), seen_in_past);
+              else
+                es_fprintf (fp, ngettext("Encrypted %d message.",
+                                         "Encrypted %d messages.",
+                                         seen_in_past), seen_in_past);
+            }
           else if (labs(stats_iter->time_ago) == 2)
             {
-              es_fprintf (fp, "in the future.");
+              if (stats_iter->time_ago > 0)
+                es_fprintf (fp, ngettext("Verified %d message in the future.",
+                                         "Verified %d messages in the future.",
+                                         seen_in_past), seen_in_past);
+              else
+                es_fprintf (fp, ngettext("Encrypted %d message in the future.",
+                                         "Encrypted %d messages in the future.",
+                                         seen_in_past), seen_in_past);
               /* Reset it.  */
               seen_in_past = 0;
             }
           else
             {
               if (labs(stats_iter->time_ago) == 3)
-                es_fprintf (fp, ngettext(" over the past day.",
-                                         " over the past %d days.",
-                                         TIME_AGO_SMALL_THRESHOLD
-                                         / TIME_AGO_UNIT_SMALL),
-                            TIME_AGO_SMALL_THRESHOLD
-                            / TIME_AGO_UNIT_SMALL);
+                {
+                  int days = 1 + stats_iter->time_ago / TIME_AGO_UNIT_SMALL;
+                  if (stats_iter->time_ago > 0)
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages verified over the past %d day: %d.",
+                                "Messages verified over the past %d days: %d.",
+                                days), days, seen_in_past);
+                  else
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages encrypted over the past %d day: %d.",
+                                "Messages encrypted over the past %d days: %d.",
+                                days), days, seen_in_past);
+                }
               else if (labs(stats_iter->time_ago) == 4)
-                es_fprintf (fp, ngettext(" over the past month.",
-                                         " over the past %d months.",
-                                         TIME_AGO_MEDIUM_THRESHOLD
-                                         / TIME_AGO_UNIT_MEDIUM),
-                            TIME_AGO_MEDIUM_THRESHOLD
-                            / TIME_AGO_UNIT_MEDIUM);
+                {
+                  int months = 1 + stats_iter->time_ago / TIME_AGO_UNIT_MEDIUM;
+                  if (stats_iter->time_ago > 0)
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages verified over the past %d month: %d.",
+                                "Messages verified over the past %d months: %d.",
+                                months), months, seen_in_past);
+                  else
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages encrypted over the past %d month: %d.",
+                                "Messages encrypted over the past %d months: %d.",
+                                months), months, seen_in_past);
+                }
               else if (labs(stats_iter->time_ago) == 5)
-                es_fprintf (fp, ngettext(" over the past year.",
-                                         " over the past %d years.",
-                                         TIME_AGO_LARGE_THRESHOLD
-                                         / TIME_AGO_UNIT_LARGE),
-                            TIME_AGO_LARGE_THRESHOLD
-                            / TIME_AGO_UNIT_LARGE);
+                {
+                  int years = 1 + stats_iter->time_ago / TIME_AGO_UNIT_LARGE;
+                  if (stats_iter->time_ago > 0)
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages verified over the past %d year: %d.",
+                                "Messages verified over the past %d years: %d.",
+                                years), years, seen_in_past);
+                  else
+                    es_fprintf
+                      (fp,
+                       ngettext("Messages encrypted over the past %d year: %d.",
+                                "Messages encrypted over the past %d years: %d.",
+                                years), years, seen_in_past);
+                }
               else if (labs(stats_iter->time_ago) == 6)
-                es_fprintf (fp, _(" in the past."));
+                {
+                  if (stats_iter->time_ago > 0)
+                    es_fprintf
+                      (fp, _("Messages verified in the past: %d."),
+                       seen_in_past);
+                  else
+                    es_fprintf
+                      (fp, _("Messages encrypted in the past: %d."),
+                       seen_in_past);
+                }
               else
                 log_assert (! "Broken SQL.\n");
             }
@@ -2182,9 +2232,15 @@ build_conflict_set (tofu_dbs_t dbs,
     int j;
     strlist_t *prevp;
     strlist_t iter_next;
-    int die[conflict_set_count];
+    int *die;
 
-    memset (die, 0, sizeof (die));
+    log_assert (conflict_set_count > 0);
+    die = xtrycalloc (conflict_set_count, sizeof *die);
+    if (!die)
+      {
+        /*err = gpg_error_from_syserror ();*/
+        xoutofcore (); /* Fixme: Let the fucntion return an error.  */
+      }
 
     for (i = 0; i < conflict_set_count; i ++)
       {
@@ -2224,6 +2280,7 @@ build_conflict_set (tofu_dbs_t dbs,
     /* We shouldn't have removed the head.  */
     log_assert (conflict_set);
     log_assert (conflict_set_count >= 1);
+    xfree (die);
   }
   xfree (kb_all);
 
@@ -2400,16 +2457,16 @@ get_policy (tofu_dbs_t dbs, PKT_public_key *pk,
   /* See if the key is signed by an ultimately trusted key.  */
   {
     int fingerprint_raw_len = strlen (fingerprint) / 2;
-    char fingerprint_raw[fingerprint_raw_len];
+    char fingerprint_raw[20];
     int len = 0;
 
-    if (fingerprint_raw_len != 20
+    if (fingerprint_raw_len != sizeof fingerprint_raw
         || ((len = hex2bin (fingerprint,
                             fingerprint_raw, fingerprint_raw_len))
             != strlen (fingerprint)))
       {
         if (DBG_TRUST)
-          log_debug ("TOFU: Bad fingerprint: %s (len: %zd, parsed: %d)\n",
+          log_debug ("TOFU: Bad fingerprint: %s (len: %zu, parsed: %d)\n",
                      fingerprint, strlen (fingerprint), len);
       }
     else
@@ -2700,7 +2757,13 @@ get_trust (ctrl_t ctrl, PKT_public_key *pk,
                          now);
     }
   else
-    trust_level = TRUST_UNDEFINED;
+    {
+      for (iter = conflict_set; iter; iter = iter->next)
+        show_statistics (dbs, iter->d, email,
+                         TOFU_POLICY_ASK, NULL, 1, now);
+
+      trust_level = TRUST_UNDEFINED;
+    }
 
   /* Mark any conflicting bindings that have an automatic policy as
    * now requiring confirmation.  Note: we do this after we ask for
@@ -2751,7 +2814,7 @@ get_trust (ctrl_t ctrl, PKT_public_key *pk,
 
 
 /* Return a malloced string of the form
- *    "7 months, 1 day, 5 minutes, 0 seconds"
+ *    "7~months"
  * The caller should replace all '~' in the returned string by a space
  * and also free the returned string.
  *
@@ -2761,127 +2824,46 @@ get_trust (ctrl_t ctrl, PKT_public_key *pk,
 static char *
 time_ago_str (long long int t)
 {
-  estream_t fp;
-  int years = 0;
-  int months = 0;
-  int days = 0;
-  int hours = 0;
-  int minutes = 0;
-  int seconds = 0;
-
-  /* The number of units that we've printed so far.  */
-  int count = 0;
-  /* The first unit that we printed (year = 0, month = 1,
-     etc.).  */
-  int first = -1;
-  /* The current unit.  */
-  int i = 0;
-
-  char *str;
-
   /* It would be nice to use a macro to do this, but gettext
      works on the unpreprocessed code.  */
 #define MIN_SECS (60)
 #define HOUR_SECS (60 * MIN_SECS)
 #define DAY_SECS (24 * HOUR_SECS)
+#define WEEK_SECS (7 * DAY_SECS)
 #define MONTH_SECS (30 * DAY_SECS)
 #define YEAR_SECS (365 * DAY_SECS)
 
-  if (t > YEAR_SECS)
-    {
-      years = t / YEAR_SECS;
-      t -= years * YEAR_SECS;
-    }
-  if (t > MONTH_SECS)
-    {
-      months = t / MONTH_SECS;
-      t -= months * MONTH_SECS;
-    }
-  if (t > DAY_SECS)
-    {
-      days = t / DAY_SECS;
-      t -= days * DAY_SECS;
-    }
-  if (t > HOUR_SECS)
-    {
-      hours = t / HOUR_SECS;
-      t -= hours * HOUR_SECS;
-    }
-  if (t > MIN_SECS)
-    {
-      minutes = t / MIN_SECS;
-      t -= minutes * MIN_SECS;
-    }
-  seconds = t;
-
-#undef MIN_SECS
-#undef HOUR_SECS
-#undef DAY_SECS
-#undef MONTH_SECS
-#undef YEAR_SECS
-
-  fp = es_fopenmem (0, "rw,samethread");
-  if (! fp)
-    log_fatal ("error creating memory stream: %s\n",
-               gpg_strerror (gpg_error_from_syserror()));
-
-  if (years)
+  if (t > 2 * YEAR_SECS)
     {
-      /* TRANSLATORS: The tilde ('~') is used here to indicate a
-       * non-breakable space  */
-      es_fprintf (fp, ngettext("%d~year", "%d~years", years), years);
-      count ++;
-      first = i;
+      long long int c = t / YEAR_SECS;
+      return xtryasprintf (ngettext("%lld~year", "%lld~years", c), c);
     }
-  i ++;
-  if ((first == -1 || i - first <= 3) && count <= 0 && months)
+  if (t > 2 * MONTH_SECS)
     {
-      if (count)
-        es_fprintf (fp, ", ");
-      es_fprintf (fp, ngettext("%d~month", "%d~months", months), months);
-      count ++;
-      first = i;
+      long long int c = t / MONTH_SECS;
+      return xtryasprintf (ngettext("%lld~month", "%lld~months", c), c);
     }
-  i ++;
-  if ((first == -1 || i - first <= 3) && count <= 0 && days)
+  if (t > 2 * WEEK_SECS)
     {
-      if (count)
-        es_fprintf (fp, ", ");
-      es_fprintf (fp, ngettext("%d~day", "%d~days", days), days);
-      count ++;
-      first = i;
+      long long int c = t / WEEK_SECS;
+      return xtryasprintf (ngettext("%lld~week", "%lld~weeks", c), c);
     }
-  i ++;
-  if ((first == -1 || i - first <= 3) && count <= 0 && hours)
+  if (t > 2 * DAY_SECS)
     {
-      if (count)
-        es_fprintf (fp, ", ");
-      es_fprintf (fp, ngettext("%d~hour", "%d~hours", hours), hours);
-      count ++;
-      first = i;
+      long long int c = t / DAY_SECS;
+      return xtryasprintf (ngettext("%lld~day", "%lld~days", c), c);
     }
-  i ++;
-  if ((first == -1 || i - first <= 3) && count <= 0 && minutes)
+  if (t > 2 * HOUR_SECS)
     {
-      if (count)
-        es_fprintf (fp, ", ");
-      es_fprintf (fp, ngettext("%d~minute", "%d~minutes", minutes), minutes);
-      count ++;
-      first = i;
+      long long int c = t / HOUR_SECS;
+      return xtryasprintf (ngettext("%lld~hour", "%lld~hours", c), c);
     }
-  i ++;
-  if ((first == -1 || i - first <= 3) && count <= 0)
+  if (t > 2 * MIN_SECS)
     {
-      if (count)
-        es_fprintf (fp, ", ");
-      es_fprintf (fp, ngettext("%d~second", "%d~seconds", seconds), seconds);
+      long long int c = t / MIN_SECS;
+      return xtryasprintf (ngettext("%lld~minute", "%lld~minutes", c), c);
     }
-
-  es_fputc (0, fp);
-  if (es_fclose_snatch (fp, (void **) &str, NULL))
-    log_fatal ("error snatching memory stream\n");
-
-  return str;
+  return xtryasprintf (ngettext("%lld~second", "%lld~seconds", t), t);
 }
 
 
@@ -2893,25 +2875,27 @@ write_stats_status (estream_t fp,
                     unsigned long signature_count,
                     unsigned long signature_first_seen,
                     unsigned long signature_most_recent,
+                    unsigned long signature_days,
                     unsigned long encryption_count,
                     unsigned long encryption_first_done,
-                    unsigned long encryption_most_recent)
+                    unsigned long encryption_most_recent,
+                    unsigned long encryption_days)
 {
   int summary;
   int validity;
-  unsigned long messages;
+  unsigned long days;
 
   /* Use the euclidean distance (m = sqrt(a^2 + b^2)) rather then the
      sum of the magnitudes (m = a + b) to ensure a balance between
      verified signatures and encrypted messages.  */
-  messages = sqrtu32 (signature_count * signature_count
-                      + encryption_count * encryption_count);
+  days = sqrtu32 (signature_days * signature_days
+                  + encryption_days * encryption_days);
 
-  if (messages < 1)
+  if (days < 1)
     validity = 1; /* Key without history.  */
-  else if (messages < 2 * BASIC_TRUST_THRESHOLD)
+  else if (days < 2 * BASIC_TRUST_THRESHOLD)
     validity = 2; /* Key with too little history.  */
-  else if (messages < 2 * FULL_TRUST_THRESHOLD)
+  else if (days < 2 * FULL_TRUST_THRESHOLD)
     validity = 3; /* Key with enough history for basic trust.  */
   else
     validity = 4; /* Key with a lot of history.  */
@@ -2923,17 +2907,17 @@ write_stats_status (estream_t fp,
 
   if (fp)
     {
-      es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:\n",
+      es_fprintf (fp, "tfs:1:%d:%lu:%lu:%s:%lu:%lu:%lu:%lu:%d:%lu:%lu:\n",
                   summary, signature_count, encryption_count,
                   tofu_policy_str (policy),
                   signature_first_seen, signature_most_recent,
                   encryption_first_done, encryption_most_recent,
-                  validity);
+                  validity, signature_days, encryption_days);
     }
   else
     {
       write_status_printf (STATUS_TOFU_STATS,
-                           "%d %lu %lu %s %lu %lu %lu %lu %d",
+                           "%d %lu %lu %s %lu %lu %lu %lu %d %lu %lu",
                            summary,
                            signature_count,
                            encryption_count,
@@ -2942,24 +2926,26 @@ write_stats_status (estream_t fp,
                            signature_most_recent,
                            encryption_first_done,
                            encryption_most_recent,
-                           validity);
+                           validity,
+                           signature_days, encryption_days);
     }
 }
 
 /* Note: If OUTFP is not NULL, this function merely prints a "tfs" record
  * to OUTFP.
  *
- * Returns whether the caller should call show_warning after iterating
- * over all user ids.
+ * POLICY is the key's policy (as returned by get_policy).
+ *
+ * Returns 0 if if ONLY_STATUS_FD is set.  Otherwise, returns whether
+ * the caller should call show_warning after iterating over all user
+ * ids.
  */
 static int
-show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
-                const char *email, const char *user_id,
-                estream_t outfp, time_t now)
+show_statistics (tofu_dbs_t dbs,
+                 const char *fingerprint, const char *email,
+                 enum tofu_policy policy,
+                estream_t outfp, int only_status_fd, time_t now)
 {
-  enum tofu_policy policy =
-    get_policy (dbs, pk, fingerprint, user_id, email, NULL, now);
-
   char *fingerprint_pp;
   int rc;
   strlist_t strlist = NULL;
@@ -2968,13 +2954,16 @@ show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
   unsigned long signature_first_seen = 0;
   unsigned long signature_most_recent = 0;
   unsigned long signature_count = 0;
+  unsigned long signature_days = 0;
   unsigned long encryption_first_done = 0;
   unsigned long encryption_most_recent = 0;
   unsigned long encryption_count = 0;
+  unsigned long encryption_days = 0;
 
   int show_warning = 0;
 
-  (void) user_id;
+  if (only_status_fd && ! is_status_enabled ())
+    return 0;
 
   fingerprint_pp = format_hexfingerprint (fingerprint, NULL, 0);
 
@@ -2994,18 +2983,38 @@ show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
       rc = gpg_error (GPG_ERR_GENERAL);
       goto out;
     }
+  rc = gpgsql_exec_printf
+    (dbs->db, strings_collect_cb, &strlist, &err,
+     "select count (*) from\n"
+     "  (select round(signatures.time / (24 * 60 * 60)) day\n"
+     "    from signatures\n"
+     "    left join bindings on signatures.binding = bindings.oid\n"
+     "    where fingerprint = %Q and email = %Q\n"
+     "    group by day);",
+     fingerprint, email);
+  if (rc)
+    {
+      log_error (_("error reading TOFU database: %s\n"), err);
+      print_further_info ("getting signature statistics (by day)");
+      sqlite3_free (err);
+      rc = gpg_error (GPG_ERR_GENERAL);
+      goto out;
+    }
 
   if (strlist)
     {
-      /* We expect exactly 3 elements.  */
+      /* We expect exactly 4 elements.  */
       log_assert (strlist->next);
       log_assert (strlist->next->next);
-      log_assert (! strlist->next->next->next);
+      log_assert (strlist->next->next->next);
+      log_assert (! strlist->next->next->next->next);
 
-      string_to_ulong (&signature_count, strlist->d, -1, __LINE__);
-      string_to_ulong (&signature_first_seen, strlist->next->d, -1, __LINE__);
-      string_to_ulong (&signature_most_recent,
+      string_to_ulong (&signature_days, strlist->d, -1, __LINE__);
+      string_to_ulong (&signature_count, strlist->next->d, -1, __LINE__);
+      string_to_ulong (&signature_first_seen,
                        strlist->next->next->d, -1, __LINE__);
+      string_to_ulong (&signature_most_recent,
+                       strlist->next->next->next->d, -1, __LINE__);
 
       free_strlist (strlist);
       strlist = NULL;
@@ -3027,18 +3036,38 @@ show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
       rc = gpg_error (GPG_ERR_GENERAL);
       goto out;
     }
+  rc = gpgsql_exec_printf
+    (dbs->db, strings_collect_cb, &strlist, &err,
+     "select count (*) from\n"
+     "  (select round(encryptions.time / (24 * 60 * 60)) day\n"
+     "    from encryptions\n"
+     "    left join bindings on encryptions.binding = bindings.oid\n"
+     "    where fingerprint = %Q and email = %Q\n"
+     "    group by day);",
+     fingerprint, email);
+  if (rc)
+    {
+      log_error (_("error reading TOFU database: %s\n"), err);
+      print_further_info ("getting encryption statistics (by day)");
+      sqlite3_free (err);
+      rc = gpg_error (GPG_ERR_GENERAL);
+      goto out;
+    }
 
   if (strlist)
     {
-      /* We expect exactly 3 elements.  */
+      /* We expect exactly 4 elements.  */
       log_assert (strlist->next);
       log_assert (strlist->next->next);
-      log_assert (! strlist->next->next->next);
+      log_assert (strlist->next->next->next);
+      log_assert (! strlist->next->next->next->next);
 
-      string_to_ulong (&encryption_count, strlist->d, -1, __LINE__);
-      string_to_ulong (&encryption_first_done, strlist->next->d, -1, __LINE__);
-      string_to_ulong (&encryption_most_recent,
+      string_to_ulong (&encryption_days, strlist->d, -1, __LINE__);
+      string_to_ulong (&encryption_count, strlist->next->d, -1, __LINE__);
+      string_to_ulong (&encryption_first_done,
                        strlist->next->next->d, -1, __LINE__);
+      string_to_ulong (&encryption_most_recent,
+                       strlist->next->next->next->d, -1, __LINE__);
 
       free_strlist (strlist);
       strlist = NULL;
@@ -3052,11 +3081,13 @@ show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
                       signature_count,
                       signature_first_seen,
                       signature_most_recent,
+                      signature_days,
                       encryption_count,
                       encryption_first_done,
-                      encryption_most_recent);
+                      encryption_most_recent,
+                      encryption_days);
 
-  if (!outfp)
+  if (!outfp && !only_status_fd)
     {
       estream_t fp;
       char *msg;
@@ -3066,56 +3097,55 @@ show_statistics (tofu_dbs_t dbs, PKT_public_key *pk, const char *fingerprint,
         log_fatal ("error creating memory stream: %s\n",
                    gpg_strerror (gpg_error_from_syserror()));
 
-      es_fprintf (fp, _("%s: "), email);
-
-      if (signature_count == 0)
-        {
-          es_fprintf (fp, _("Verified %ld signatures"), 0L);
-          es_fputc ('\n', fp);
-        }
-      else
+      if (signature_count == 0 && encryption_count == 0)
         {
-          char *first_seen_ago_str = time_ago_str (now - signature_first_seen);
-
-          /* TRANSLATORS: The final %s is replaced by a string like
-             "7 months, 1 day, 5 minutes, 0 seconds". */
           es_fprintf (fp,
-                      ngettext("Verified %ld signature in the past %s",
-                               "Verified %ld signatures in the past %s",
-                               signature_count),
-                      signature_count, first_seen_ago_str);
-
-          xfree (first_seen_ago_str);
-        }
-
-      if (encryption_count == 0)
-        {
-          es_fprintf (fp, _(", and encrypted %ld messages"), 0L);
+                      _("%s: Verified 0~signatures and encrypted 0~messages."),
+                      email);
         }
       else
         {
-          char *first_done_ago_str = time_ago_str (now - encryption_first_done);
+          if (signature_count == 0)
+            es_fprintf (fp, _("%s: Verified 0 signatures."), email);
+          else
+            {
+              /* TRANSLATORS: The final %s is replaced by a string like
+                 "7~months". */
+              char *ago_str = time_ago_str (now - signature_first_seen);
+              es_fprintf
+                (fp,
+                 ngettext("%s: Verified %ld~signature in the past %s.",
+                          "%s: Verified %ld~signatures in the past %s.",
+                          signature_count),
+                 email, signature_count, ago_str);
+              xfree (ago_str);
+            }
 
-          /* TRANSLATORS: The final %s is replaced by a string like
-             "7 months, 1 day, 5 minutes, 0 seconds". */
-          es_fprintf (fp,
-                      ngettext(", and encrypted %ld message in the past %s",
-                               ", and encrypted %ld messages in the past %s",
-                               encryption_count),
-                      encryption_count, first_done_ago_str);
+          es_fputs ("  ", fp);
 
-          xfree (first_done_ago_str);
+          if (encryption_count == 0)
+            es_fprintf (fp, _("Encrypted 0 messages."));
+          else
+            {
+              char *ago_str = time_ago_str (now - encryption_first_done);
+
+              /* TRANSLATORS: The final %s is replaced by a string like
+                 "7~months". */
+              es_fprintf (fp,
+                          ngettext("Encrypted %ld~message in the past %s.",
+                                   "Encrypted %ld~messages in the past %s.",
+                                   encryption_count),
+                          encryption_count, ago_str);
+              xfree (ago_str);
+            }
         }
 
       if (opt.verbose)
         {
           es_fputs ("  ", fp);
-          es_fputc ('(', fp);
-          es_fprintf (fp, _("policy: %s"), tofu_policy_str (policy));
-          es_fputs (").\n", fp);
+          es_fprintf (fp, _("(policy: %s)"), tofu_policy_str (policy));
         }
-      else
-        es_fputs (".\n", fp);
+      es_fputs ("\n", fp);
 
 
       {
@@ -3449,7 +3479,7 @@ tofu_register_encryption (ctrl_t ctrl,
       free_user_id_list = 1;
 
       if (! user_id_list)
-        log_info (_("WARNING: Encrypting to %s, which has no"
+        log_info (_("WARNING: Encrypting to %s, which has no "
                     "non-revoked user ids.\n"),
                   keystr (pk->keyid));
     }
@@ -3585,6 +3615,7 @@ tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
   tofu_dbs_t dbs;
   char *fingerprint;
   char *email;
+  enum tofu_policy policy;
 
   if (!*user_id)
     return 0;  /* No TOFU stats possible for an empty ID.  */
@@ -3599,8 +3630,9 @@ tofu_write_tfs_record (ctrl_t ctrl, estream_t fp,
 
   fingerprint = hexfingerprint (pk, NULL, 0);
   email = email_from_user_id (user_id);
+  policy = get_policy (dbs, pk, fingerprint, user_id, email, NULL, now);
 
-  show_statistics (dbs, pk, fingerprint, email, user_id, fp, now);
+  show_statistics (dbs, fingerprint, email, policy, fp, 0, now);
 
   xfree (email);
   xfree (fingerprint);
@@ -3675,8 +3707,13 @@ tofu_get_validity (ctrl_t ctrl, PKT_public_key *pk, strlist_t user_id_list,
         bindings_valid ++;
 
       if (may_ask && tl != TRUST_ULTIMATE && tl != TRUST_EXPIRED)
-        need_warning |=
-          show_statistics (dbs, pk, fingerprint, email, user_id->d, NULL, now);
+        {
+          enum tofu_policy policy =
+            get_policy (dbs, pk, fingerprint, user_id->d, email, NULL, now);
+
+          need_warning |=
+            show_statistics (dbs, fingerprint, email, policy, NULL, 0, now);
+        }
 
       if (tl == TRUST_NEVER)
         trust_level = TRUST_NEVER;
@@ -3797,23 +3834,6 @@ tofu_set_policy (ctrl_t ctrl, kbnode_t kb, enum tofu_policy policy)
   return err;
 }
 
-/* Set the TOFU policy for all non-revoked user ids in the KEY with
-   the key id KEYID to POLICY.
-
-   If no key is available with the specified key id, then this
-   function returns GPG_ERR_NO_PUBKEY.
-
-   Returns 0 on success and an error code otherwise.  */
-gpg_error_t
-tofu_set_policy_by_keyid (ctrl_t ctrl, u32 *keyid, enum tofu_policy policy)
-{
-  kbnode_t keyblock = get_pubkeyblock (keyid);
-  if (! keyblock)
-    return gpg_error (GPG_ERR_NO_PUBKEY);
-
-  return tofu_set_policy (ctrl, keyblock, policy);
-}
-
 /* Return the TOFU policy for the specified binding in *POLICY.  If no
    policy has been set for the binding, sets *POLICY to
    TOFU_POLICY_NONE.