Allow for default algorithms in a parameter file
[gnupg.git] / g10 / keylist.c
index 6425989..4a76ee0 100644 (file)
@@ -1,12 +1,12 @@
-/* keylist.c
- * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003,
- *               2004, 2005 Free Software Foundation, Inc.
+/* keylist.c - print keys
+ * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
+ *               2008 Free Software Foundation, Inc.
  *
  * This file is part of GnuPG.
  *
  * GnuPG is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
+ * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
  *
  * GnuPG is distributed in the hope that it will be useful,
@@ -15,8 +15,7 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
+ * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
 #include <config.h>
 #include <string.h>
 #include <errno.h>
 #include <assert.h>
+#ifdef HAVE_DOSISH_SYSTEM
+#include <fcntl.h> /* for setmode() */
+#endif
 
+#include "gpg.h"
 #include "options.h"
 #include "packet.h"
-#include "errors.h"
+#include "status.h"
 #include "keydb.h"
-#include "memory.h"
 #include "photoid.h"
 #include "util.h"
 #include "ttyio.h"
@@ -40,7 +42,8 @@
 #include "status.h"
 
 static void list_all(int);
-static void list_one( STRLIST names, int secret);
+static void list_one( strlist_t names, int secret);
+static void locate_one (strlist_t names);
 static void print_card_serialno (PKT_secret_key *sk);
 
 struct sig_stats
@@ -50,16 +53,17 @@ struct sig_stats
   int oth_err;
 };
 
-static FILE *attrib_fp=NULL;
+/* The stream used to write attribute packets to.  */
+static FILE *attrib_fp = NULL;
 
 /****************
  * List the keys
  * If list is NULL, all available keys are listed
  */
 void
-public_key_list( STRLIST list )
+public_key_list( strlist_t list, int locate_mode )
 {
-  if(opt.with_colons)
+  if (opt.with_colons)
     {
       byte trust_model,marginals,completes,cert_depth;
       ulong created,nextcheck;
@@ -102,14 +106,17 @@ public_key_list( STRLIST list )
      which is associated with the inode of a deleted file.  */
   check_trustdb_stale ();
 
-  if( !list )
-    list_all(0);
+  if (locate_mode)
+    locate_one (list);
+  else if (!list)
+    list_all (0);
   else
-    list_one( list, 0 );
+    list_one (list, 0);
 }
 
+
 void
-secret_key_list( STRLIST list )
+secret_key_list( strlist_t list )
 {
     check_trustdb_stale ();
 
@@ -133,7 +140,7 @@ print_seckey_info (PKT_secret_key *sk)
              pubkey_letter (sk->pubkey_algo),
              keystr(keyid), datestr_from_sk (sk), p);
     
-  m_free (p);
+  xfree (p);
 }
 
 /* Print information about the public key.  With FP passed as NULL,
@@ -164,7 +171,7 @@ print_pubkey_info (FILE *fp, PKT_public_key *pk)
                 nbits_from_pk (pk), pubkey_letter (pk->pubkey_algo),
                 keystr(keyid), datestr_from_pk (pk), p);
 
-  m_free (p);
+  xfree (p);
 }
 
 
@@ -248,7 +255,7 @@ show_policy_url(PKT_signature *sig,int indent,int mode)
   const byte *p;
   size_t len;
   int seq=0,crit;
-  FILE *fp=mode?log_stream():stdout;
+  FILE *fp=mode?log_get_stream():stdout;
 
   while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_POLICY,&len,&seq,&crit)))
     {
@@ -289,7 +296,7 @@ show_keyserver_url(PKT_signature *sig,int indent,int mode)
   const byte *p;
   size_t len;
   int seq=0,crit;
-  FILE *fp=mode?log_stream():stdout;
+  FILE *fp=mode?log_get_stream():stdout;
 
   while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&len,&seq,&crit)))
     {
@@ -331,71 +338,55 @@ show_keyserver_url(PKT_signature *sig,int indent,int mode)
 void
 show_notation(PKT_signature *sig,int indent,int mode,int which)
 {
-  const byte *p;
-  size_t len;
-  int seq=0,crit;
-  FILE *fp=mode?log_stream():stdout;
+  FILE *fp=mode?log_get_stream():stdout;
+  struct notation *nd,*notations;
 
   if(which==0)
     which=3;
 
-  /* There may be multiple notations in the same sig. */
-
-  while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
-    if(len>=8)
-      {
-       int n1,n2;
-
-       n1=(p[4]<<8)|p[5];
-       n2=(p[6]<<8)|p[7];
-
-       if(8+n1+n2!=len)
-         {
-           log_info(_("WARNING: invalid notation data found\n"));
-           continue;
-         }
+  notations=sig_to_notation(sig);
 
-       if(mode!=2)
-         {
-           int has_at=!!memchr(p+8,'@',n1);
+  /* There may be multiple notations in the same sig. */
+  for(nd=notations;nd;nd=nd->next)
+    {
+      if(mode!=2)
+       {
+         int has_at=!!strchr(nd->name,'@');
+
+         if((which&1 && !has_at) || (which&2 && has_at))
+           {
+             int i;
+             const char *str;
+
+             for(i=0;i<indent;i++)
+               putchar(' ');
+
+             if(nd->flags.critical)
+               str=_("Critical signature notation: ");
+             else
+               str=_("Signature notation: ");
+             if(mode)
+               log_info("%s",str);
+             else
+               printf("%s",str);
+             /* This is all UTF8 */
+             print_utf8_string(fp,nd->name,strlen(nd->name));
+             fprintf(fp,"=");
+             print_utf8_string(fp,nd->value,strlen(nd->value));
+             fprintf(fp,"\n");
+           }
+       }
 
-           if((which&1 && !has_at) || (which&2 && has_at))
-             {
-               int i;
-               const char *str;
-
-               for(i=0;i<indent;i++)
-                 putchar(' ');
-
-               /* This is UTF8 */
-               if(crit)
-                 str=_("Critical signature notation: ");
-               else
-                 str=_("Signature notation: ");
-               if(mode)
-                 log_info("%s",str);
-               else
-                 printf("%s",str);
-               print_utf8_string(fp,p+8,n1);
-               fprintf(fp,"=");
-
-               if(*p&0x80)
-                 print_utf8_string(fp,p+8+n1,n2);
-               else
-                 fprintf(fp,"[ %s ]",_("not human readable"));
-
-               fprintf(fp,"\n");
-             }
-         }
+      if(mode)
+       {
+         write_status_buffer(STATUS_NOTATION_NAME,
+                             nd->name,strlen(nd->name),0);
+         write_status_buffer(STATUS_NOTATION_DATA,
+                             nd->value,strlen(nd->value),50);
+       }
+    }
 
-       if(mode)
-         {
-           write_status_buffer ( STATUS_NOTATION_NAME, p+8   , n1, 0 );
-           write_status_buffer ( STATUS_NOTATION_DATA, p+8+n1, n2, 50 );
-         }
-      }
-  else
-    log_info(_("WARNING: invalid notation data found\n"));
+  free_notation(notations);
 }
 
 static void
@@ -477,7 +468,7 @@ list_all( int secret )
 
 
 static void
-list_one( STRLIST names, int secret )
+list_one( strlist_t names, int secret )
 {
     int rc = 0;
     KBNODE keyblock = NULL;
@@ -544,6 +535,45 @@ list_one( STRLIST names, int secret )
       print_signature_stats(&stats);
 }
 
+
+static void
+locate_one (strlist_t names)
+{
+  int rc = 0;
+  strlist_t sl;
+  GETKEY_CTX ctx = NULL;
+  KBNODE keyblock = NULL;
+  struct sig_stats stats;
+
+  memset (&stats,0,sizeof(stats));
+    
+  for (sl=names; sl; sl = sl->next)
+    {
+      rc = get_pubkey_byname (&ctx, NULL, sl->d, &keyblock, NULL, 1, 0);
+      if (rc)
+        {
+          if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY)
+            log_error ("error reading key: %s\n", g10_errstr(rc) );
+       }
+      else
+        {
+          do 
+            {
+              list_keyblock (keyblock, 0, opt.fingerprint,
+                             opt.check_sigs? &stats : NULL );
+              release_kbnode (keyblock);
+            } 
+          while ( ctx && !get_pubkey_next (ctx, NULL, &keyblock));
+          get_pubkey_end (ctx);
+          ctx = NULL;
+       } 
+    }
+  
+  if (opt.check_sigs && !opt.with_colons)
+    print_signature_stats (&stats);
+}
+
+
 static void
 print_key_data( PKT_public_key *pk )
 {
@@ -564,6 +594,7 @@ print_capabilities (PKT_public_key *pk, PKT_secret_key *sk, KBNODE keyblock)
   if(pk || (sk && sk->protect.s2k.mode!=1001))
     {
       unsigned int use = pk? pk->pubkey_usage : sk->pubkey_usage;
+      int c_printed = 0;
     
       if ( use & PUBKEY_USAGE_ENC )
         putchar ('e');
@@ -572,9 +603,19 @@ print_capabilities (PKT_public_key *pk, PKT_secret_key *sk, KBNODE keyblock)
        {
          putchar ('s');
          if( pk? pk->is_primary : sk->is_primary )
-           putchar ('c');
+            {
+              putchar ('c');
+              /* The PUBKEY_USAGE_CERT flag was introduced later and
+                 we used to always print 'c' for a primary key.  To
+                 avoid any regression here we better track whether we
+                 printed 'c' already.  */
+              c_printed = 1;
+            }
        }
 
+      if ( (use & PUBKEY_USAGE_CERT) && !c_printed )
+        putchar ('c');
+
       if ( (use & PUBKEY_USAGE_AUTH) )
         putchar ('a');
     }
@@ -600,6 +641,8 @@ print_capabilities (PKT_public_key *pk, PKT_secret_key *sk, KBNODE keyblock)
                        if(pk->is_primary)
                          cert = 1;
                      }
+                    if ( pk->pubkey_usage & PUBKEY_USAGE_CERT )
+                      cert = 1;
                     if ( (pk->pubkey_usage & PUBKEY_USAGE_AUTH) )
                       auth = 1;
                 }
@@ -617,6 +660,8 @@ print_capabilities (PKT_public_key *pk, PKT_secret_key *sk, KBNODE keyblock)
                        if(sk->is_primary)
                          cert = 1;
                      }
+                    if ( (sk->pubkey_usage & PUBKEY_USAGE_CERT) )
+                        cert = 1;
                     if ( (sk->pubkey_usage & PUBKEY_USAGE_AUTH) )
                         auth = 1;
                 }
@@ -719,6 +764,7 @@ dump_attribs(const PKT_user_id *uid,PKT_public_key *pk,PKT_secret_key *sk)
        }
 
       fwrite(uid->attribs[i].data,uid->attribs[i].len,1,attrib_fp);
+      fflush (attrib_fp);
     }
 }
 
@@ -789,7 +835,7 @@ list_keyblock_print ( KBNODE keyblock, int secret, int fpr, void *opaque )
        else if(pk->has_expired)
          {
            printf(" [");
-           printf(_("expired: %s)"),expirestr_from_pk(pk));
+           printf(_("expired: %s"),expirestr_from_pk(pk));
            printf("]");
          }
        else if(pk->expiredate)
@@ -856,7 +902,7 @@ list_keyblock_print ( KBNODE keyblock, int secret, int fpr, void *opaque )
            putchar('\n');
 
            if((opt.list_options&LIST_SHOW_PHOTOS) && uid->attribs!=NULL)
-             show_photos(uid->attribs,uid->numattribs,pk,sk);
+             show_photos(uid->attribs,uid->numattribs,pk,sk,uid);
        }
        else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
          {
@@ -930,12 +976,13 @@ list_keyblock_print ( KBNODE keyblock, int secret, int fpr, void *opaque )
            if( stats ) {
                 /*fflush(stdout);*/
                rc = check_key_signature( keyblock, node, NULL );
-               switch( rc ) {
-                case 0:                 sigrc = '!'; break;
-                case G10ERR_BAD_SIGN:   stats->inv_sigs++; sigrc = '-'; break;
-                case G10ERR_NO_PUBKEY: 
-                case G10ERR_UNU_PUBKEY: stats->no_key++; continue;
-                default:                stats->oth_err++; sigrc = '%'; break;
+               switch( gpg_err_code (rc) ) {
+                case 0:                sigrc = '!'; break;
+                case GPG_ERR_BAD_SIGNATURE:
+                   stats->inv_sigs++; sigrc = '-'; break;
+                case GPG_ERR_NO_PUBKEY: 
+                case GPG_ERR_UNUSABLE_PUBKEY: stats->no_key++; continue;
+                default:               stats->oth_err++; sigrc = '%'; break;
                }
 
                /* TODO: Make sure a cached sig record here still has
@@ -985,7 +1032,7 @@ list_keyblock_print ( KBNODE keyblock, int secret, int fpr, void *opaque )
                size_t n;
                char *p = get_user_id( sig->keyid, &n );
                 print_utf8_string( stdout, p, n );
-               m_free(p);
+               xfree(p);
            }
            putchar('\n');
 
@@ -1008,369 +1055,350 @@ list_keyblock_print ( KBNODE keyblock, int secret, int fpr, void *opaque )
     putchar('\n');
 }
 
+void
+print_revokers(PKT_public_key *pk)
+{
+  /* print the revoker record */
+  if( !pk->revkey && pk->numrevkeys )
+    BUG();
+  else
+    {
+      int i,j;
+
+      for (i=0; i < pk->numrevkeys; i++)
+       {
+         byte *p;
+
+         printf ("rvk:::%d::::::", pk->revkey[i].algid);
+         p = pk->revkey[i].fpr;
+         for (j=0; j < 20; j++, p++ )
+           printf ("%02X", *p);
+         printf (":%02x%s:\n", pk->revkey[i].class,
+                 (pk->revkey[i].class&0x40)?"s":"");
+       }
+    }
+}
 
 static void
 list_keyblock_colon( KBNODE keyblock, int secret, int fpr )
 {
-    int rc = 0;
-    KBNODE kbctx;
-    KBNODE node;
-    PKT_public_key *pk;
-    PKT_secret_key *sk;
-    u32 keyid[2];
-    int any=0;
-    int trustletter = 0;
-    int ulti_hack = 0;
-    int i;
+  int rc = 0;
+  KBNODE kbctx;
+  KBNODE node;
+  PKT_public_key *pk;
+  PKT_secret_key *sk;
+  u32 keyid[2];
+  int trustletter = 0;
+  int ulti_hack = 0;
+  int i;
 
-    /* get the keyid from the keyblock */
-    node = find_kbnode( keyblock, secret? PKT_SECRET_KEY : PKT_PUBLIC_KEY );
-    if( !node ) {
-       log_error("Oops; key lost!\n");
-       dump_kbnode( keyblock );
-       return;
+  /* get the keyid from the keyblock */
+  node = find_kbnode( keyblock, secret? PKT_SECRET_KEY : PKT_PUBLIC_KEY );
+  if ( !node )
+    {
+      log_error("Oops; key lost!\n");
+      dump_kbnode( keyblock );
+      return;
     }
 
-    if( secret ) {
-       pk = NULL;
-       sk = node->pkt->pkt.secret_key;
-       keyid_from_sk( sk, keyid );
-        printf("sec::%u:%d:%08lX%08lX:%s:%s:::",
-                   nbits_from_sk( sk ),
-                   sk->pubkey_algo,
-                   (ulong)keyid[0],(ulong)keyid[1],
-                   colon_datestr_from_sk( sk ),
-                   colon_strtime (sk->expiredate)
-                   /* fixme: add LID here */ );
+  if ( secret )
+    {
+      pk = NULL;
+      sk = node->pkt->pkt.secret_key;
+      keyid_from_sk ( sk, keyid );
+      printf ("sec::%u:%d:%08lX%08lX:%s:%s:::",
+              nbits_from_sk( sk ),
+              sk->pubkey_algo,
+              (ulong)keyid[0],(ulong)keyid[1],
+              colon_datestr_from_sk( sk ),
+              colon_strtime (sk->expiredate)
+              /* fixme: add LID here */ );
     }
-    else {
-       pk = node->pkt->pkt.public_key;
-       sk = NULL;
-       keyid_from_pk( pk, keyid );
-        fputs( "pub:", stdout );
-        if ( !pk->is_valid )
+  else
+    {
+      pk = node->pkt->pkt.public_key;
+      sk = NULL;
+      keyid_from_pk( pk, keyid );
+      fputs( "pub:", stdout );
+      if ( !pk->is_valid )
+        putchar ('i');
+      else if ( pk->is_revoked )
+        putchar ('r');
+      else if ( pk->has_expired )
+        putchar ('e');
+      else if ( opt.fast_list_mode || opt.no_expensive_trust_checks ) 
+      ;
+      else 
+        {
+          trustletter = get_validity_info ( pk, NULL );
+          if ( trustletter == 'u' )
+            ulti_hack = 1;
+          putchar(trustletter);
+        }
+      printf (":%u:%d:%08lX%08lX:%s:%s::",
+              nbits_from_pk( pk ),
+              pk->pubkey_algo,
+              (ulong)keyid[0],(ulong)keyid[1],
+              colon_datestr_from_pk( pk ),
+              colon_strtime (pk->expiredate) );
+      if ( !opt.fast_list_mode && !opt.no_expensive_trust_checks  )
+        putchar( get_ownertrust_info(pk) );
+      putchar(':');
+    }
+
+  putchar (':');
+  putchar (':');
+  print_capabilities (pk, sk, keyblock);
+  if (secret)
+    {
+      putchar (':'); /* End of field 13. */
+      putchar (':'); /* End of field 14. */
+      if (sk->protect.s2k.mode == 1001)
+        putchar ('#'); /* Key is just a stub. */
+      else if (sk->protect.s2k.mode == 1002)
+        {
+          /* Key is stored on an external token (card) or handled by
+             the gpg-agent.  Print the serial number of that token
+             here. */
+          for (i=0; i < sk->protect.ivlen; i++)
+            printf ("%02X", sk->protect.iv[i]);
+        }
+      putchar (':'); /* End of field 15. */
+    }
+  putchar('\n');
+  if (pk)
+    print_revokers (pk);
+  if (fpr)
+    print_fingerprint (pk, sk, 0);
+  if (opt.with_key_data)
+    print_key_data (pk);
+
+
+  for ( kbctx=NULL; (node=walk_kbnode( keyblock, &kbctx, 0)) ; )
+    {
+      if ( node->pkt->pkttype == PKT_USER_ID && !opt.fast_list_mode )
+        {
+          char *str;
+          PKT_user_id *uid=node->pkt->pkt.user_id;
+
+          if (attrib_fp && node->pkt->pkt.user_id->attrib_data != NULL)
+            dump_attribs (node->pkt->pkt.user_id,pk,sk);
+          /*
+           * Fixme: We need a is_valid flag here too 
+           */
+          str = uid->attrib_data? "uat":"uid";
+          /* If we're listing a secret key, leave out the validity
+             values for now.  This is handled better in 1.9. */
+          if (sk)
+            printf ("%s:::::",str);
+          else if ( uid->is_revoked )
+            printf ("%s:r::::",str);
+          else if ( uid->is_expired )
+            printf ("%s:e::::",str);
+          else if ( opt.no_expensive_trust_checks )
+            printf ("%s:::::",str);
+          else 
+            {
+              int uid_validity;
+                
+              if ( pk && !ulti_hack )
+                uid_validity=get_validity_info (pk, uid);
+              else
+                uid_validity = 'u';
+              printf ("%s:%c::::",str,uid_validity);
+            }
+            
+          printf ("%s:", colon_strtime (uid->created));
+          printf ("%s:", colon_strtime (uid->expiredate));
+            
+          namehash_from_uid (uid);
+
+          for (i=0; i < 20; i++ )
+            printf ("%02X",uid->namehash[i]);
+            
+          printf ("::");
+
+          if (uid->attrib_data)
+            printf ("%u %lu",uid->numattribs,uid->attrib_len);
+          else
+            print_string (stdout,uid->name,uid->len, ':' );
+          putchar (':');
+          putchar ('\n');
+        }
+      else if ( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) 
+        {
+          u32 keyid2[2];
+          PKT_public_key *pk2 = node->pkt->pkt.public_key;
+            
+          keyid_from_pk ( pk2, keyid2 );
+          fputs ("sub:", stdout );
+          if ( !pk2->is_valid )
             putchar ('i');
-        else if ( pk->is_revoked )
+          else if ( pk2->is_revoked )
             putchar ('r');
-        else if ( pk->has_expired )
+          else if ( pk2->has_expired )
             putchar ('e');
-        else if ( opt.fast_list_mode || opt.no_expensive_trust_checks ) 
+          else if ( opt.fast_list_mode || opt.no_expensive_trust_checks )
             ;
-        else {
-            trustletter = get_validity_info ( pk, NULL );
-            if( trustletter == 'u' )
-                ulti_hack = 1;
-            putchar(trustletter);
+          else
+            {
+              /* TRUSTLETTER should always be defined here. */
+              if (trustletter)
+                printf ("%c", trustletter );
+            }
+          printf(":%u:%d:%08lX%08lX:%s:%s:::::",
+                 nbits_from_pk( pk2 ),
+                 pk2->pubkey_algo,
+                 (ulong)keyid2[0],(ulong)keyid2[1],
+                 colon_datestr_from_pk( pk2 ),
+                 colon_strtime (pk2->expiredate)
+                 /* fixme: add LID and ownertrust here */
+                 );
+          print_capabilities (pk2, NULL, NULL);
+          putchar ('\n');
+          if ( fpr > 1 )
+            print_fingerprint ( pk2, NULL, 0 );
+          if ( opt.with_key_data )
+            print_key_data( pk2 );
         }
-        printf(":%u:%d:%08lX%08lX:%s:%s::",
-                   nbits_from_pk( pk ),
-                   pk->pubkey_algo,
-                   (ulong)keyid[0],(ulong)keyid[1],
-                   colon_datestr_from_pk( pk ),
-                   colon_strtime (pk->expiredate) );
-        if( !opt.fast_list_mode && !opt.no_expensive_trust_checks  )
-            putchar( get_ownertrust_info(pk) );
-           putchar(':');
-    }
-    
-    if (opt.fixed_list_mode) {
-        /* do not merge the first uid with the primary key */
-        putchar(':');
-        putchar(':');
-        print_capabilities (pk, sk, keyblock);
-        if (secret) {
+      else if( node->pkt->pkttype == PKT_SECRET_SUBKEY )
+        {
+          u32 keyid2[2];
+          PKT_secret_key *sk2 = node->pkt->pkt.secret_key;
+
+          keyid_from_sk ( sk2, keyid2 );
+          printf ("ssb::%u:%d:%08lX%08lX:%s:%s:::::",
+                  nbits_from_sk( sk2 ),
+                  sk2->pubkey_algo,
+                  (ulong)keyid2[0],(ulong)keyid2[1],
+                  colon_datestr_from_sk( sk2 ),
+                  colon_strtime (sk2->expiredate)
+                  /* fixme: add LID */ );
+          print_capabilities (NULL, sk2, NULL);
           putchar(':'); /* End of field 13. */
           putchar(':'); /* End of field 14. */
-          if (sk->protect.s2k.mode == 1001)
-            putchar('#'); /* Key is just a stub. */
-          else if (sk->protect.s2k.mode == 1002) {
-            /* Key is stored on an external token (card) or handled by
-               the gpg-agent.  Print the serial number of that token
-               here. */
-            for (i=0; i < sk->protect.ivlen; i++)
-              printf ("%02X", sk->protect.iv[i]);
-          }
+          if (sk2->protect.s2k.mode == 1001)
+            putchar ('#'); /* Key is just a stub. */
+          else if (sk2->protect.s2k.mode == 1002)
+            {
+              /* Key is stored on an external token (card) or handled by
+                 the gpg-agent.  Print the serial number of that token
+                 here. */
+              for (i=0; i < sk2->protect.ivlen; i++)
+                printf ("%02X", sk2->protect.iv[i]);
+            }
           putchar(':'); /* End of field 15. */
+          putchar ('\n');
+        
+          if ( fpr > 1 )
+            print_fingerprint ( NULL, sk2, 0 );
         }
-        putchar('\n');
-        if( fpr )
-            print_fingerprint( pk, sk, 0 );
-        if( opt.with_key_data )
-            print_key_data( pk );
-        any = 1;
-    }
-
-
-    for( kbctx=NULL; (node=walk_kbnode( keyblock, &kbctx, 0)) ; ) {
-       if( node->pkt->pkttype == PKT_USER_ID && !opt.fast_list_mode ) {
-           PKT_user_id *uid=node->pkt->pkt.user_id;
-           if(attrib_fp && node->pkt->pkt.user_id->attrib_data!=NULL)
-             dump_attribs(node->pkt->pkt.user_id,pk,sk);
-            /*
-             * Fixme: We need a is_valid flag here too 
-             */
-           if( any ) {
-               char *str=uid->attrib_data?"uat":"uid";
-               /* If we're listing a secret key, leave out the
-                  validity values for now.  This is handled better in
-                  1.9. */
-               if ( sk )
-                   printf("%s:::::",str);
-                else if ( uid->is_revoked )
-                   printf("%s:r::::",str);
-                else if ( uid->is_expired )
-                   printf("%s:e::::",str);
-               else if ( opt.no_expensive_trust_checks )
-                   printf("%s:::::",str);
-                else {
-                   int uid_validity;
+      else if ( opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE )
+        {
+          PKT_signature *sig = node->pkt->pkt.signature;
+          int sigrc,fprokay=0;
+          char *sigstr;
+          size_t fplen;
+          byte fparray[MAX_FINGERPRINT_LEN];
+        
+          if ( sig->sig_class == 0x20 || sig->sig_class == 0x28
+               || sig->sig_class == 0x30 )
+            sigstr = "rev";
+          else if ( (sig->sig_class&~3) == 0x10 )
+            sigstr = "sig";
+          else if ( sig->sig_class == 0x18 )
+            sigstr = "sig";
+          else if ( sig->sig_class == 0x1F )
+            sigstr = "sig";
+          else 
+            {
+              printf ("sig::::::::::%02x%c:\n",
+                      sig->sig_class, sig->flags.exportable?'x':'l');
+              continue;
+            }
 
-                   if( pk && !ulti_hack )
-                     uid_validity=get_validity_info (pk, uid);
-                   else
-                       uid_validity = 'u';
-                   printf("%s:%c::::",str,uid_validity);
+          if ( opt.check_sigs )
+            {
+              PKT_public_key *signer_pk=NULL;
+            
+              fflush (stdout);
+              if (opt.no_sig_cache)
+                signer_pk = xmalloc_clear (sizeof(PKT_public_key));
+            
+              rc = check_key_signature2 ( keyblock, node, NULL, signer_pk,
+                                          NULL, NULL, NULL );
+              switch ( gpg_err_code (rc) )
+                {
+                case 0:                              sigrc = '!'; break;
+                case GPG_ERR_BAD_SIGNATURE:   sigrc = '-'; break;
+                case GPG_ERR_NO_PUBKEY: 
+                case GPG_ERR_UNUSABLE_PUBKEY: sigrc = '?'; break;
+                default:                     sigrc = '%'; break;
                 }
 
-               printf("%s:",colon_strtime(uid->created));
-               printf("%s:",colon_strtime(uid->expiredate));
-
-               namehash_from_uid(uid);
-
-               for(i=0; i < 20; i++ )
-                 printf("%02X",uid->namehash[i]);
-
-               printf("::");
-           }
-           if(uid->attrib_data)
-             printf("%u %lu",uid->numattribs,uid->attrib_len);
-            else
-             print_string(stdout,uid->name,uid->len, ':' );
-            putchar(':');
-           if (any)
-                putchar('\n');
-            else {
-                putchar(':');
-                print_capabilities (pk, sk, keyblock);
-                putchar('\n');
-               if( fpr )
-                   print_fingerprint( pk, sk, 0 );
-               if( opt.with_key_data )
-                   print_key_data( pk );
-               any = 1;
-           }
-       }
-       else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
-           u32 keyid2[2];
-           PKT_public_key *pk2 = node->pkt->pkt.public_key;
-
-           if( !any ) {
-                putchar(':');
-                putchar(':');
-                print_capabilities (pk, sk, keyblock);
-                putchar('\n');
-               if( fpr )
-                   print_fingerprint( pk, sk, 0 ); /* of the main key */
-               any = 1;
-           }
-
-           keyid_from_pk( pk2, keyid2 );
-            fputs ("sub:", stdout );
-            if ( !pk2->is_valid )
-                putchar ('i');
-            else if ( pk2->is_revoked )
-                putchar ('r');
-            else if ( pk2->has_expired )
-                putchar ('e');
-            else if ( opt.fast_list_mode || opt.no_expensive_trust_checks )
-                ;
-            else {
-               /* trustletter should always be defined here */
-               if(trustletter)
-                 printf("%c", trustletter );
+              if (opt.no_sig_cache)
+                {
+                  if (!rc)
+                    {
+                      fingerprint_from_pk (signer_pk, fparray, &fplen);
+                      fprokay = 1;
+                    }
+                  free_public_key(signer_pk);
+                }
             }
-            printf(":%u:%d:%08lX%08lX:%s:%s:::::",
-                       nbits_from_pk( pk2 ),
-                       pk2->pubkey_algo,
-                       (ulong)keyid2[0],(ulong)keyid2[1],
-                       colon_datestr_from_pk( pk2 ),
-                       colon_strtime (pk2->expiredate)
-                       /* fixme: add LID and ownertrust here */
-                                               );
-            print_capabilities (pk2, NULL, NULL);
-            putchar('\n');
-           if( fpr > 1 )
-               print_fingerprint( pk2, NULL, 0 );
-           if( opt.with_key_data )
-               print_key_data( pk2 );
-       }
-       else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
-           u32 keyid2[2];
-           PKT_secret_key *sk2 = node->pkt->pkt.secret_key;
-
-           if( !any ) {
-                putchar(':');
-                putchar(':');
-                print_capabilities (pk, sk, keyblock);
-               putchar('\n');
-               if( fpr )
-                   print_fingerprint( pk, sk, 0 ); /* of the main key */
-               any = 1;
-           }
-
-           keyid_from_sk( sk2, keyid2 );
-            printf("ssb::%u:%d:%08lX%08lX:%s:%s:::::",
-                       nbits_from_sk( sk2 ),
-                       sk2->pubkey_algo,
-                       (ulong)keyid2[0],(ulong)keyid2[1],
-                       colon_datestr_from_sk( sk2 ),
-                       colon_strtime (sk2->expiredate)
-                   /* fixme: add LID */ );
-            print_capabilities (NULL, sk2, NULL);
-            if (opt.fixed_list_mode) {
-              /* We print the serial number only in fixed list mode
-                 for the primary key so, so avoid questions we print
-                 it for subkeys also only in this mode.  There is no
-                 technical reason, though. */
-              putchar(':'); /* End of field 13. */
-              putchar(':'); /* End of field 14. */
-              if (sk2->protect.s2k.mode == 1001)
-                putchar('#'); /* Key is just a stub. */
-              else if (sk2->protect.s2k.mode == 1002) {
-                /* Key is stored on an external token (card) or handled by
-                   the gpg-agent.  Print the serial number of that token
-                   here. */
-                for (i=0; i < sk2->protect.ivlen; i++)
-                  printf ("%02X", sk2->protect.iv[i]);
-              }
-              putchar(':'); /* End of field 15. */
+          else 
+            {
+              rc = 0;
+              sigrc = ' ';
+            }
+          fputs ( sigstr, stdout );
+          putchar (':');
+          if ( sigrc != ' ' )
+            putchar (sigrc);
+          printf ("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
+                  (ulong)sig->keyid[0], (ulong)sig->keyid[1],
+                  colon_datestr_from_sig(sig),
+                  colon_expirestr_from_sig(sig));
+
+          if (sig->trust_depth || sig->trust_value)
+            printf("%d %d",sig->trust_depth,sig->trust_value);
+          printf (":");
+
+          if (sig->trust_regexp)
+            print_string (stdout,sig->trust_regexp,
+                          strlen(sig->trust_regexp),':');
+          printf(":");
+        
+          if ( sigrc == '%' )
+            printf("[%s] ", g10_errstr(rc) );
+          else if ( sigrc == '?' )
+            ;
+          else if ( !opt.fast_list_mode )
+            {
+              size_t n;
+              char *p = get_user_id( sig->keyid, &n );
+              print_string( stdout, p, n, ':' );
+              xfree(p);
+            }
+          printf (":%02x%c:", sig->sig_class,sig->flags.exportable?'x':'l');
+        
+          if (opt.no_sig_cache && opt.check_sigs && fprokay)
+            {
+              putchar (':');
+            
+              for (i=0; i < fplen ; i++ )
+                printf ("%02X", fparray[i] );
+            
+              putchar (':');
             }
-            putchar ('\n');
-           if( fpr > 1 )
-              print_fingerprint( NULL, sk2, 0 );
-       }
-       else if( opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE ) {
-           PKT_signature *sig = node->pkt->pkt.signature;
-           int sigrc,fprokay=0;
-            char *sigstr;
-           size_t fplen;
-           byte fparray[MAX_FINGERPRINT_LEN];
-
-           if( !any ) { /* no user id, (maybe a revocation follows)*/
-               if( sig->sig_class == 0x20 )
-                   fputs("[revoked]:", stdout);
-               else if( sig->sig_class == 0x18 )
-                   fputs("[key binding]:", stdout);
-               else if( sig->sig_class == 0x28 )
-                   fputs("[subkey revoked]:", stdout);
-                else
-                    putchar (':');
-                putchar(':');
-                print_capabilities (pk, sk, keyblock);
-                putchar('\n');
-               if( fpr )
-                   print_fingerprint( pk, sk, 0 );
-               any=1;
-           }
-
-           if( sig->sig_class == 0x20 || sig->sig_class == 0x28
-                                      || sig->sig_class == 0x30 )
-              sigstr = "rev";
-           else if( (sig->sig_class&~3) == 0x10 )
-              sigstr = "sig";
-           else if( sig->sig_class == 0x18 )
-              sigstr = "sig";
-           else if( sig->sig_class == 0x1F )
-              sigstr = "sig";
-           else {
-                printf ("sig::::::::::%02x%c:\n",
-                        sig->sig_class, sig->flags.exportable?'x':'l');
-               continue;
-           }
-           if( opt.check_sigs ) {
-               PKT_public_key *signer_pk=NULL;
-
-               fflush(stdout);
-               if(opt.no_sig_cache)
-                 signer_pk=m_alloc_clear(sizeof(PKT_public_key));
-
-               rc = check_key_signature2( keyblock, node, NULL, signer_pk,
-                                          NULL, NULL, NULL );
-               switch( rc ) {
-                 case 0:                  sigrc = '!'; break;
-                 case G10ERR_BAD_SIGN:    sigrc = '-'; break;
-                 case G10ERR_NO_PUBKEY: 
-                 case G10ERR_UNU_PUBKEY:  sigrc = '?'; break;
-                 default:                 sigrc = '%'; break;
-               }
-
-               if(opt.no_sig_cache)
-                 {
-                   if(rc==0)
-                     {
-                       fingerprint_from_pk (signer_pk, fparray, &fplen);
-                       fprokay=1;
-                     }
-                   free_public_key(signer_pk);
-                 }
-           }
-           else {
-               rc = 0;
-               sigrc = ' ';
-           }
-            fputs( sigstr, stdout );
-            putchar(':');
-            if( sigrc != ' ' )
-                putchar(sigrc);
-            printf("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
-                  (ulong)sig->keyid[0], (ulong)sig->keyid[1],
-                  colon_datestr_from_sig(sig),
-                  colon_expirestr_from_sig(sig));
-
-           if(sig->trust_depth || sig->trust_value)
-             printf("%d %d",sig->trust_depth,sig->trust_value);
-           printf(":");
-
-           if(sig->trust_regexp)
-             print_string(stdout,sig->trust_regexp,
-                          strlen(sig->trust_regexp),':');
-           printf(":");
-
-           if( sigrc == '%' )
-               printf("[%s] ", g10_errstr(rc) );
-           else if( sigrc == '?' )
-               ;
-           else if ( !opt.fast_list_mode ) {
-               size_t n;
-               char *p = get_user_id( sig->keyid, &n );
-                print_string( stdout, p, n, ':' );
-               m_free(p);
-           }
-            printf(":%02x%c:", sig->sig_class,sig->flags.exportable?'x':'l');
-
-           if(opt.no_sig_cache && opt.check_sigs && fprokay)
-             {
-               printf(":");
-
-               for (i=0; i < fplen ; i++ )
-                 printf ("%02X", fparray[i] );
-
-               printf(":");
-             }
-
-           printf("\n");
-
-           if(opt.show_subpackets)
-             print_subpackets_colon(sig);
 
-           /* fixme: check or list other sigs here */
-       }
-    }
-    if( !any ) {/* oops, no user id */
-        putchar(':');
-        putchar(':');
-        print_capabilities (pk, sk, keyblock);
-       putchar('\n');
+          printf ("\n");
+        
+          if (opt.show_subpackets)
+            print_subpackets_colon (sig);
+          
+          /* fixme: check or list other sigs here */
+        }
     }
 }
 
@@ -1378,15 +1406,16 @@ list_keyblock_colon( KBNODE keyblock, int secret, int fpr )
  * Reorder the keyblock so that the primary user ID (and not attribute
  * packet) comes first.  Fixme: Replace this by a generic sort
  * function.  */
-void
-reorder_keyblock (KBNODE keyblock)
+static void
+do_reorder_keyblock (KBNODE keyblock,int attr)
 {
     KBNODE primary = NULL, primary0 = NULL, primary2 = NULL;
     KBNODE last, node;
 
     for (node=keyblock; node; primary0=node, node = node->next) {
        if( node->pkt->pkttype == PKT_USER_ID &&
-           !node->pkt->pkt.user_id->attrib_data &&
+           ((attr && node->pkt->pkt.user_id->attrib_data) ||
+            (!attr && !node->pkt->pkt.user_id->attrib_data)) &&
             node->pkt->pkt.user_id->is_primary ) {
             primary = primary2 = node;
             for (node=node->next; node; primary2=node, node = node->next ) {
@@ -1418,6 +1447,13 @@ reorder_keyblock (KBNODE keyblock)
 }
 
 void
+reorder_keyblock (KBNODE keyblock)
+{
+  do_reorder_keyblock(keyblock,1);
+  do_reorder_keyblock(keyblock,0);
+}
+
+void
 list_keyblock( KBNODE keyblock, int secret, int fpr, void *opaque )
 {
     reorder_keyblock (keyblock);
@@ -1468,14 +1504,14 @@ print_fingerprint (PKT_public_key *pk, PKT_secret_key *sk, int mode )
       {
        if(sk)
          {
-           PKT_secret_key *primary_sk=m_alloc_clear(sizeof(*primary_sk));
+           PKT_secret_key *primary_sk=xmalloc_clear(sizeof(*primary_sk));
            get_seckey(primary_sk,sk->main_keyid);
            print_fingerprint(NULL,primary_sk,mode|0x80);
            free_secret_key(primary_sk);
          }
        else
          {
-           PKT_public_key *primary_pk=m_alloc_clear(sizeof(*primary_pk));
+           PKT_public_key *primary_pk=xmalloc_clear(sizeof(*primary_pk));
            get_pubkey(primary_pk,pk->main_keyid);
            print_fingerprint(primary_pk,NULL,mode|0x80);
            free_public_key(primary_pk);
@@ -1483,7 +1519,7 @@ print_fingerprint (PKT_public_key *pk, PKT_secret_key *sk, int mode )
       }
 
     if (mode == 1) {
-        fp = log_stream ();
+        fp = log_get_stream ();
        if(primary)
          text = _("Primary key fingerprint:");
        else
@@ -1593,29 +1629,35 @@ print_card_serialno (PKT_secret_key *sk)
 
 
 
-void set_attrib_fd(int fd)
+void
+set_attrib_fd (int fd)
 {
   static int last_fd=-1;
 
   if ( fd != -1 && last_fd == fd )
     return;
 
-  if ( attrib_fp && attrib_fp != stdout && attrib_fp != stderr )
+  if ( attrib_fp && attrib_fp != stdout && attrib_fp != stderr 
+       && attrib_fp != log_get_stream () )
     fclose (attrib_fp);
   attrib_fp = NULL;
   if ( fd == -1 ) 
     return;
 
+#ifdef HAVE_DOSISH_SYSTEM
+  setmode (fd, O_BINARY);
+#endif
   if( fd == 1 )
     attrib_fp = stdout;
   else if( fd == 2 )
     attrib_fp = stderr;
   else
-    attrib_fp = fdopen( fd, "wb" );
-  if( !attrib_fp ) {
-    log_fatal("can't open fd %d for attribute output: %s\n",
-             fd, strerror(errno));
-  }
-
+    attrib_fp = fdopen (fd, "wb");
+  if (!attrib_fp) 
+    {
+      log_fatal("can't open fd %d for attribute output: %s\n",
+                fd, strerror(errno));
+    }
+  
   last_fd = fd;
 }