chiark / gitweb /
asshelp.c: add a lot of debug logging
[gnupg2.git] / g10 / gpgcompose.c
1 /* gpgcompose.c - Maintainer tool to create OpenPGP messages by hand.
2  * Copyright (C) 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 #include <config.h>
21 #include <errno.h>
22
23 #include "gpg.h"
24 #include "packet.h"
25 #include "keydb.h"
26 #include "main.h"
27 #include "options.h"
28
29 static int do_debug;
30 #define debug(fmt, ...) \
31   do { if (do_debug) log_debug (fmt, ##__VA_ARGS__); } while (0)
32 \f
33 /* --encryption, for instance, adds a filter in front of out.  There
34    is an operator (--encryption-pop) to end this.  We use the
35    following infrastructure to make it easy to pop the state.  */
36 struct filter
37 {
38   void *func;
39   void *context;
40   int pkttype;
41   int partial_block_mode;
42   struct filter *next;
43 };
44
45 static struct filter *filters;
46
47 static void
48 filter_push (iobuf_t out, void *func, void *context,
49              int type, int partial_block_mode)
50 {
51   gpg_error_t err;
52   struct filter *f = xmalloc_clear (sizeof (*f));
53   f->next = filters;
54   f->func = func;
55   f->context = context;
56   f->pkttype = type;
57   f->partial_block_mode = partial_block_mode;
58
59   filters = f;
60
61   err = iobuf_push_filter (out, func, context);
62   if (err)
63     log_fatal ("Adding filter: %s\n", gpg_strerror (err));
64 }
65
66 static void
67 filter_pop (iobuf_t out, int expected_type)
68 {
69   gpg_error_t err;
70   struct filter *f = filters;
71
72   log_assert (f);
73
74   if (f->pkttype != expected_type)
75     log_fatal ("Attempted to pop a %s container, "
76                "but current container is a %s container.\n",
77                pkttype_str (f->pkttype), pkttype_str (expected_type));
78
79   if (f->pkttype == PKT_ENCRYPTED || f->pkttype == PKT_ENCRYPTED_MDC)
80     {
81       err = iobuf_pop_filter (out, f->func, f->context);
82       if (err)
83         log_fatal ("Popping encryption filter: %s\n", gpg_strerror (err));
84     }
85   else
86     log_fatal ("FILTERS appears to be corrupted.\n");
87
88   if (f->partial_block_mode)
89     iobuf_set_partial_body_length_mode (out, 0);
90
91   filters = f->next;
92   xfree (f);
93 }
94 \f
95 /* Return if CIPHER_ID is a valid cipher.  */
96 static int
97 valid_cipher (int cipher_id)
98 {
99   return (cipher_id == CIPHER_ALGO_IDEA
100           || cipher_id == CIPHER_ALGO_3DES
101           || cipher_id == CIPHER_ALGO_CAST5
102           || cipher_id == CIPHER_ALGO_BLOWFISH
103           || cipher_id == CIPHER_ALGO_AES
104           || cipher_id == CIPHER_ALGO_AES192
105           || cipher_id == CIPHER_ALGO_AES256
106           || cipher_id == CIPHER_ALGO_TWOFISH
107           || cipher_id == CIPHER_ALGO_CAMELLIA128
108           || cipher_id == CIPHER_ALGO_CAMELLIA192
109           || cipher_id == CIPHER_ALGO_CAMELLIA256);
110 }
111 \f
112 /* Parse a session key encoded as a string of the form x:HEXDIGITS
113    where x is the algorithm id.  (This is the format emitted by gpg
114    --show-session-key.)  */
115 struct session_key
116 {
117   int algo;
118   int keylen;
119   char *key;
120 };
121
122 static struct session_key
123 parse_session_key (const char *option, char *p, int require_algo)
124 {
125   char *tail;
126   struct session_key sk;
127
128   memset (&sk, 0, sizeof (sk));
129
130   /* Check for the optional "cipher-id:" at the start of the
131      string.  */
132   errno = 0;
133   sk.algo = strtol (p, &tail, 10);
134   if (! errno && tail && *tail == ':')
135     {
136       if (! valid_cipher (sk.algo))
137         log_info ("%s: %d is not a known cipher (but using anyways)\n",
138                   option, sk.algo);
139       p = tail + 1;
140     }
141   else if (require_algo)
142     log_fatal ("%s: Session key must have the form algo:HEXCHARACTERS.\n",
143                option);
144   else
145     sk.algo = 0;
146
147   /* Ignore a leading 0x.  */
148   if (p[0] == '0' && p[1] == 'x')
149     p += 2;
150
151   if (strlen (p) % 2 != 0)
152     log_fatal ("%s: session key must consist of an even number of hexadecimal characters.\n",
153                option);
154
155   sk.keylen = strlen (p) / 2;
156   sk.key = xmalloc (sk.keylen);
157
158   if (hex2bin (p, sk.key, sk.keylen) == -1)
159     log_fatal ("%s: Session key must only contain hexadecimal characters\n",
160                option);
161
162   return sk;
163 }
164 \f
165 /* A callback.
166
167    OPTION_STR is the option that was matched.  ARGC is the number of
168    arguments following the option and ARGV are those arguments.
169    (Thus, argv[0] is the first string following the option and
170    argv[-1] is the option.)
171
172    COOKIE is the opaque value passed to process_options.  */
173 typedef int (*option_prcessor_t) (const char *option_str,
174                                   int argc, char *argv[],
175                                   void *cookie);
176
177 struct option
178 {
179   /* The option that this matches.  This must start with "--" or be
180      the empty string.  The empty string matches bare arguments.  */
181   const char *option;
182   /* The function to call to process this option.  */
183   option_prcessor_t func;
184   /* Documentation.  */
185   const char *help;
186 };
187
188 /* Merge two lists of options.  Note: this makes a shallow copy!  The
189    caller must xfree() the result.  */
190 static struct option *
191 merge_options (struct option a[], struct option b[])
192 {
193   int i, j;
194   struct option *c;
195
196   for (i = 0; a[i].option; i ++)
197     ;
198   for (j = 0; b[j].option; j ++)
199     ;
200
201   c = xmalloc ((i + j + 1) * sizeof (struct option));
202   memcpy (c, a, i * sizeof (struct option));
203   memcpy (&c[i], b, j * sizeof (struct option));
204   c[i + j].option = NULL;
205
206   if (a[i].help && b[j].help)
207     c[i + j].help = xasprintf ("%s\n\n%s", a[i].help, b[j].help);
208   else if (a[i].help)
209     c[i + j].help = a[i].help;
210   else if (b[j].help)
211     c[i + j].help = b[j].help;
212
213   return c;
214 }
215
216 /* Returns whether ARG is an option.  All options start with --.  */
217 static int
218 is_option (const char *arg)
219 {
220   return arg[0] == '-' && arg[1] == '-';
221 }
222
223 /* OPTIONS is a NULL terminated array of struct option:s.  Finds the
224    entry that is the same as ARG.  Returns -1 if no entry is found.
225    The empty string option matches bare arguments.  */
226 static int
227 match_option (const struct option options[], const char *arg)
228 {
229   int i;
230   int bare_arg = ! is_option (arg);
231
232   for (i = 0; options[i].option; i ++)
233     if ((! bare_arg && strcmp (options[i].option, arg) == 0)
234         /* Non-options match the empty string.  */
235         || (bare_arg && options[i].option[0] == '\0'))
236       return i;
237
238   return -1;
239 }
240
241 static void
242 show_help (struct option options[])
243 {
244   int i;
245   int max_length = 0;
246   int space;
247
248   for (i = 0; options[i].option; i ++)
249     {
250       const char *option = options[i].option[0] ? options[i].option : "ARG";
251       int l = strlen (option);
252       if (l > max_length)
253         max_length = l;
254     }
255
256   space = 72 - (max_length + 2);
257   if (space < 40)
258     space = 40;
259
260   for (i = 0; ; i ++)
261     {
262       const char *option = options[i].option;
263       const char *help = options[i].help;
264
265       int l;
266       int j;
267       char *tmp;
268       char *formatted;
269       char *p;
270       char *newline;
271
272       if (! option && ! help)
273         break;
274
275       if (option)
276         {
277           const char *o = option[0] ? option : "ARG";
278           l = strlen (o);
279           fprintf (stderr, "%s", o);
280         }
281
282       if (! help)
283         {
284           fputc ('\n', stderr);
285           continue;
286         }
287
288       if (option)
289         for (j = l; j < max_length + 2; j ++)
290           fputc (' ', stderr);
291
292 #define BOLD_START "\033[1m"
293 #define NORMAL_RESTORE "\033[0m"
294 #define BOLD(x) BOLD_START x NORMAL_RESTORE
295
296       if (! option || options[i].func)
297         tmp = (char *) help;
298       else
299         tmp = xasprintf ("%s " BOLD("(Unimplemented.)"), help);
300
301       if (! option)
302         space = 72;
303       formatted = format_text (tmp, 0, space, space + 4);
304
305       if (tmp != help)
306         xfree (tmp);
307
308       if (! option)
309         {
310           fprintf (stderr, "\n%s\n", formatted);
311           break;
312         }
313
314       for (p = formatted;
315            p && *p;
316            p = (*newline == '\0') ? newline : newline + 1)
317         {
318           newline = strchr (p, '\n');
319           if (! newline)
320             newline = &p[strlen (p)];
321
322           l = (size_t) newline - (size_t) p;
323
324           if (p != formatted)
325             for (j = 0; j < max_length + 2; j ++)
326               fputc (' ', stderr);
327
328           fwrite (p, l, 1, stderr);
329           fputc ('\n', stderr);
330         }
331
332       xfree (formatted);
333   }
334 }
335
336 /* Return value is number of consumed argv elements.  */
337 static int
338 process_options (const char *parent_option,
339                  struct option break_options[],
340                  struct option local_options[], void *lcookie,
341                  struct option global_options[], void *gcookie,
342                  int argc, char *argv[])
343 {
344   int i;
345   for (i = 0; i < argc; i ++)
346     {
347       int j;
348       struct option *option;
349       void *cookie;
350       int bare_arg;
351       option_prcessor_t func;
352       int consumed;
353
354       if (break_options)
355         {
356           j = match_option (break_options, argv[i]);
357           if (j != -1)
358             /* Match.  Break out.  */
359             return i;
360         }
361
362       j = match_option (local_options, argv[i]);
363       if (j == -1)
364         {
365           if (global_options)
366             j = match_option (global_options, argv[i]);
367           if (j == -1)
368             {
369               if (strcmp (argv[i], "--help") == 0)
370                 {
371                   if (! global_options)
372                     show_help (local_options);
373                   else
374                     {
375                       struct option *combined
376                         = merge_options (local_options, global_options);
377                       show_help (combined);
378                       xfree (combined);
379                     }
380                   g10_exit (0);
381                 }
382
383               if (parent_option)
384                 log_fatal ("%s: Unknown option: %s\n", parent_option, argv[i]);
385               else
386                 log_fatal ("Unknown option: %s\n", argv[i]);
387             }
388
389           option = &global_options[j];
390           cookie = gcookie;
391         }
392       else
393         {
394           option = &local_options[j];
395           cookie = lcookie;
396         }
397
398       bare_arg = strcmp (option->option, "") == 0;
399
400       func = option->func;
401       if (! func)
402         {
403           if (bare_arg)
404             log_fatal ("Bare arguments unimplemented.\n");
405           else
406             log_fatal ("Unimplemented option: %s\n",
407                        option->option);
408         }
409
410       consumed = func (bare_arg ? parent_option : argv[i],
411                        argc - i - !bare_arg, &argv[i + !bare_arg],
412                        cookie);
413       i += consumed;
414       if (bare_arg)
415         i --;
416     }
417
418   return i;
419 }
420 \f
421 /* The keys, subkeys, user ids and user attributes in the order that
422    they were added.  */
423 PACKET components[20];
424 /* The number of components.  */
425 int ncomponents;
426
427 static int
428 add_component (int pkttype, void *component)
429 {
430   int i = ncomponents ++;
431
432   log_assert (i < sizeof (components) / sizeof (components[0]));
433   log_assert (pkttype == PKT_PUBLIC_KEY
434               || pkttype == PKT_PUBLIC_SUBKEY
435               || pkttype == PKT_SECRET_KEY
436               || pkttype == PKT_SECRET_SUBKEY
437               || pkttype == PKT_USER_ID
438               || pkttype == PKT_ATTRIBUTE);
439
440   components[i].pkttype = pkttype;
441   components[i].pkt.generic = component;
442
443   return i;
444 }
445
446 static void
447 dump_component (PACKET *pkt)
448 {
449   struct kbnode_struct kbnode;
450
451   if (! do_debug)
452     return;
453
454   memset (&kbnode, 0, sizeof (kbnode));
455   kbnode.pkt = pkt;
456   dump_kbnode (&kbnode);
457 }
458
459 /* Returns the first primary key in COMPONENTS or NULL if there is
460    none.  */
461 static PKT_public_key *
462 primary_key (void)
463 {
464   int i;
465   for (i = 0; i < ncomponents; i ++)
466     if (components[i].pkttype == PKT_PUBLIC_KEY)
467       return components[i].pkt.public_key;
468   return NULL;
469 }
470 \f
471 /* The last session key (updated when adding a SK-ESK, PK-ESK or SED
472    packet.  */
473 static DEK session_key;
474 \f
475 static int user_id (const char *option, int argc, char *argv[],
476                     void *cookie);
477 static int public_key (const char *option, int argc, char *argv[],
478                        void *cookie);
479 static int sk_esk (const char *option, int argc, char *argv[],
480                    void *cookie);
481 static int pk_esk (const char *option, int argc, char *argv[],
482                    void *cookie);
483 static int encrypted (const char *option, int argc, char *argv[],
484                       void *cookie);
485 static int encrypted_pop (const char *option, int argc, char *argv[],
486                           void *cookie);
487 static int literal (const char *option, int argc, char *argv[],
488                     void *cookie);
489 static int signature (const char *option, int argc, char *argv[],
490                       void *cookie);
491 static int copy (const char *option, int argc, char *argv[],
492                  void *cookie);
493
494 static struct option major_options[] = {
495   { "--user-id", user_id, "Create a user id packet." },
496   { "--public-key", public_key, "Create a public key packet." },
497   { "--private-key", NULL, "Create a private key packet." },
498   { "--public-subkey", public_key, "Create a subkey packet." },
499   { "--private-subkey", NULL, "Create a private subkey packet." },
500   { "--sk-esk", sk_esk,
501     "Create a symmetric-key encrypted session key packet." },
502   { "--pk-esk", pk_esk,
503     "Create a public-key encrypted session key packet." },
504   { "--encrypted", encrypted, "Create a symmetrically encrypted data packet." },
505   { "--encrypted-mdc", encrypted,
506     "Create a symmetrically encrypted and integrity protected data packet." },
507   { "--encrypted-pop", encrypted_pop,
508     "Pop an encryption container." },
509   { "--compressed", NULL, "Create a compressed data packet." },
510   { "--literal", literal, "Create a literal (plaintext) data packet." },
511   { "--signature", signature, "Create a signature packet." },
512   { "--onepass-sig", NULL, "Create a one-pass signature packet." },
513   { "--copy", copy, "Copy the specified file." },
514   { NULL, NULL,
515     "To get more information about a given command, use:\n\n"
516     "  $ gpgcompose --command --help to list a command's options."},
517 };
518 \f
519 static struct option global_options[] = {
520   { NULL, NULL, NULL },
521 };
522 \f
523 /* Make our lives easier and use a static limit for the user name.
524    10k is way more than enough anyways... */
525 const int user_id_max_len = 10 * 1024;
526
527 static int
528 user_id_name (const char *option, int argc, char *argv[], void *cookie)
529 {
530   PKT_user_id *uid = cookie;
531   int l;
532
533   if (argc == 0)
534     log_fatal ("Usage: %s USER_ID\n", option);
535
536   if (uid->len)
537     log_fatal ("Attempt to set user id multiple times.\n");
538
539   l = strlen (argv[0]);
540   if (l > user_id_max_len)
541     log_fatal ("user id too long (max: %d)\n", user_id_max_len);
542
543   memcpy (uid->name, argv[0], l);
544   uid->name[l] = 0;
545   uid->len = l;
546
547   return 1;
548 }
549
550 static struct option user_id_options[] = {
551   { "", user_id_name,
552     "Set the user id.  This is usually in the format "
553     "\"Name (comment) <email@example.org>\"" },
554   { NULL, NULL,
555     "Example:\n\n"
556     "  $ gpgcompose --user-id \"USERID\" | " GPG_NAME " --list-packets" }
557 };
558
559 static int
560 user_id (const char *option, int argc, char *argv[], void *cookie)
561 {
562   iobuf_t out = cookie;
563   gpg_error_t err;
564   PKT_user_id *uid = xmalloc_clear (sizeof (*uid) + user_id_max_len);
565   int c = add_component (PKT_USER_ID, uid);
566   int processed;
567
568   processed = process_options (option,
569                                major_options,
570                                user_id_options, uid,
571                                global_options, NULL,
572                                argc, argv);
573
574   if (! uid->len)
575     log_fatal ("%s: user id not given", option);
576
577   err = build_packet (out, &components[c]);
578   if (err)
579     log_fatal ("Serializing user id packet: %s\n", gpg_strerror (err));
580
581   debug ("Wrote user id packet:\n");
582   dump_component (&components[c]);
583
584   return processed;
585 }
586 \f
587 static int
588 pk_search_terms (const char *option, int argc, char *argv[], void *cookie)
589 {
590   gpg_error_t err;
591   KEYDB_HANDLE hd;
592   KEYDB_SEARCH_DESC desc;
593   kbnode_t kb;
594   PKT_public_key *pk = cookie;
595   PKT_public_key *pk_ref;
596   int i;
597
598   if (argc == 0)
599     log_fatal ("Usage: %s KEYID\n", option);
600
601   if (pk->pubkey_algo)
602     log_fatal ("%s: multiple keys provided\n", option);
603
604   err = classify_user_id (argv[0], &desc, 0);
605   if (err)
606     log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
607
608   hd = keydb_new ();
609
610   err = keydb_search (hd, &desc, 1, NULL);
611   if (err)
612     log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err));
613
614   err = keydb_get_keyblock (hd, &kb);
615   if (err)
616     log_fatal ("retrieving keyblock for '%s': %s\n",
617                argv[0], gpg_strerror (err));
618
619   keydb_release (hd);
620
621   pk_ref = kb->pkt->pkt.public_key;
622
623   /* Copy the timestamp (if not already set), algo and public key
624      parameters.  */
625   if (! pk->timestamp)
626     pk->timestamp = pk_ref->timestamp;
627   pk->pubkey_algo = pk_ref->pubkey_algo;
628   for (i = 0; i < pubkey_get_npkey (pk->pubkey_algo); i ++)
629     pk->pkey[i] = gcry_mpi_copy (pk_ref->pkey[i]);
630
631   release_kbnode (kb);
632
633   return 1;
634 }
635
636 static int
637 pk_timestamp (const char *option, int argc, char *argv[], void *cookie)
638 {
639   PKT_public_key *pk = cookie;
640   char *tail = NULL;
641
642   if (argc == 0)
643     log_fatal ("Usage: %s TIMESTAMP\n", option);
644
645   errno = 0;
646   pk->timestamp = parse_timestamp (argv[0], &tail);
647   if (errno || (tail && *tail))
648     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
649
650   return 1;
651 }
652
653 #define TIMESTAMP_HELP \
654   "Either as seconds since the epoch or as an ISO 8601 formatted " \
655   "string (yyyymmddThhmmss, where the T is a literal)."
656
657 static struct option pk_options[] = {
658   { "--timestamp", pk_timestamp,
659     "The creation time.  " TIMESTAMP_HELP },
660   { "", pk_search_terms,
661     "The key to copy the creation time and public key parameters from."  },
662   { NULL, NULL,
663     "Example:\n\n"
664     "  $ gpgcompose --public-key $KEYID --user-id \"USERID\" \\\n"
665     "  | " GPG_NAME " --list-packets" }
666 };
667
668 static int
669 public_key (const char *option, int argc, char *argv[], void *cookie)
670 {
671   gpg_error_t err;
672   iobuf_t out = cookie;
673   PKT_public_key *pk;
674   int c;
675   int processed;
676   int t = (strcmp (option, "--public-key") == 0
677            ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY);
678
679   (void) option;
680
681   pk = xmalloc_clear (sizeof (*pk));
682   pk->version = 4;
683
684   c = add_component (t, pk);
685
686   processed = process_options (option,
687                                major_options,
688                                pk_options, pk,
689                                global_options, NULL,
690                                argc, argv);
691
692   if (! pk->pubkey_algo)
693     log_fatal ("%s: key to extract public key parameters from not given",
694                option);
695
696   /* Clear the keyid in case we updated one of the relevant fields
697      after accessing it.  */
698   pk->keyid[0] = pk->keyid[1] = 0;
699
700   err = build_packet (out, &components[c]);
701   if (err)
702     log_fatal ("serializing %s packet: %s\n",
703                t == PKT_PUBLIC_KEY ? "public key" : "subkey",
704                gpg_strerror (err));
705
706   debug ("Wrote %s packet:\n",
707          t == PKT_PUBLIC_KEY ? "public key" : "subkey");
708   dump_component (&components[c]);
709
710   return processed;
711 }
712 \f
713 struct signinfo
714 {
715   /* Key with which to sign.  */
716   kbnode_t issuer_kb;
717   PKT_public_key *issuer_pk;
718
719   /* Overrides the issuer's key id.  */
720   u32 issuer_keyid[2];
721   /* Sets the issuer's keyid to the primary key's key id.  */
722   int issuer_keyid_self;
723
724   /* Key to sign.  */
725   PKT_public_key *pk;
726   /* Subkey to sign.  */
727   PKT_public_key *sk;
728   /* User id to sign.  */
729   PKT_user_id *uid;
730
731   int class;
732   int digest_algo;
733   u32 timestamp;
734   u32 key_expiration;
735
736   byte *cipher_algorithms;
737   int cipher_algorithms_len;
738   byte *digest_algorithms;
739   int digest_algorithms_len;
740   byte *compress_algorithms;
741   int compress_algorithms_len;
742
743   u32 expiration;
744
745   int exportable_set;
746   int exportable;
747
748   int revocable_set;
749   int revocable;
750
751   int trust_level_set;
752   byte trust_args[2];
753
754   char *trust_scope;
755
756   struct revocation_key *revocation_key;
757   int nrevocation_keys;
758
759   struct notation *notations;
760
761   byte *key_server_preferences;
762   int key_server_preferences_len;
763
764   char *key_server;
765
766   int primary_user_id_set;
767   int primary_user_id;
768
769   char *policy_uri;
770
771   byte *key_flags;
772   int key_flags_len;
773
774   char *signers_user_id;
775
776   byte reason_for_revocation_code;
777   char *reason_for_revocation;
778
779   byte *features;
780   int features_len;
781
782   /* Whether to corrupt the signature.  */
783   int corrupt;
784 };
785
786 static int
787 sig_issuer (const char *option, int argc, char *argv[], void *cookie)
788 {
789   gpg_error_t err;
790   KEYDB_HANDLE hd;
791   KEYDB_SEARCH_DESC desc;
792   struct signinfo *si = cookie;
793
794   if (argc == 0)
795     log_fatal ("Usage: %s KEYID\n", option);
796
797   if (si->issuer_pk)
798     log_fatal ("%s: multiple keys provided\n", option);
799
800   err = classify_user_id (argv[0], &desc, 0);
801   if (err)
802     log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
803
804   hd = keydb_new ();
805
806   err = keydb_search (hd, &desc, 1, NULL);
807   if (err)
808     log_fatal ("looking up '%s': %s\n", argv[0], gpg_strerror (err));
809
810   err = keydb_get_keyblock (hd, &si->issuer_kb);
811   if (err)
812     log_fatal ("retrieving keyblock for '%s': %s\n",
813                argv[0], gpg_strerror (err));
814
815   keydb_release (hd);
816
817   si->issuer_pk = si->issuer_kb->pkt->pkt.public_key;
818
819   return 1;
820 }
821
822 static int
823 sig_issuer_keyid (const char *option, int argc, char *argv[], void *cookie)
824 {
825   gpg_error_t err;
826   KEYDB_SEARCH_DESC desc;
827   struct signinfo *si = cookie;
828
829   if (argc == 0)
830     log_fatal ("Usage: %s KEYID|self\n", option);
831
832   if (si->issuer_keyid[0] || si->issuer_keyid[1] || si->issuer_keyid_self)
833     log_fatal ("%s given multiple times.\n", option);
834
835   if (strcasecmp (argv[0], "self") == 0)
836     {
837       si->issuer_keyid_self = 1;
838       return 1;
839     }
840
841   err = classify_user_id (argv[0], &desc, 0);
842   if (err)
843     log_fatal ("search terms '%s': %s\n", argv[0], gpg_strerror (err));
844
845   if (desc.mode != KEYDB_SEARCH_MODE_LONG_KID)
846     log_fatal ("%s is not a valid long key id.\n", argv[0]);
847
848   keyid_copy (si->issuer_keyid, desc.u.kid);
849
850   return 1;
851 }
852
853 static int
854 sig_pk (const char *option, int argc, char *argv[], void *cookie)
855 {
856   struct signinfo *si = cookie;
857   int i;
858   char *tail = NULL;
859
860   if (argc == 0)
861     log_fatal ("Usage: %s COMPONENT_INDEX\n", option);
862
863   errno = 0;
864   i = strtoul (argv[0], &tail, 10);
865   if (errno || (tail && *tail))
866     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
867
868   if (i >= ncomponents)
869     log_fatal ("%d: No such component (have %d components so far)\n",
870                i, ncomponents);
871   if (! (components[i].pkttype == PKT_PUBLIC_KEY
872          || components[i].pkttype == PKT_PUBLIC_SUBKEY))
873     log_fatal ("Component %d is not a public key or a subkey.", i);
874
875   if (strcmp (option, "--pk") == 0)
876     {
877       if (si->pk)
878         log_fatal ("%s already given.\n", option);
879       si->pk = components[i].pkt.public_key;
880     }
881   else if (strcmp (option, "--sk") == 0)
882     {
883       if (si->sk)
884         log_fatal ("%s already given.\n", option);
885       si->sk = components[i].pkt.public_key;
886     }
887   else
888     log_fatal ("Cannot handle %s\n", option);
889
890   return 1;
891 }
892
893 static int
894 sig_user_id (const char *option, int argc, char *argv[], void *cookie)
895 {
896   struct signinfo *si = cookie;
897   int i;
898   char *tail = NULL;
899
900   if (argc == 0)
901     log_fatal ("Usage: %s COMPONENT_INDEX\n", option);
902   if (si->uid)
903     log_fatal ("%s already given.\n", option);
904
905   errno = 0;
906   i = strtoul (argv[0], &tail, 10);
907   if (errno || (tail && *tail))
908     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
909
910   if (i >= ncomponents)
911     log_fatal ("%d: No such component (have %d components so far)\n",
912                i, ncomponents);
913   if (! (components[i].pkttype != PKT_USER_ID
914          || components[i].pkttype == PKT_ATTRIBUTE))
915     log_fatal ("Component %d is not a public key or a subkey.", i);
916
917   si->uid = components[i].pkt.user_id;
918
919   return 1;
920 }
921
922 static int
923 sig_class (const char *option, int argc, char *argv[], void *cookie)
924 {
925   struct signinfo *si = cookie;
926   int i;
927   char *tail = NULL;
928
929   if (argc == 0)
930     log_fatal ("Usage: %s CLASS\n", option);
931
932   errno = 0;
933   i = strtoul (argv[0], &tail, 0);
934   if (errno || (tail && *tail))
935     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
936
937   si->class = i;
938
939   return 1;
940 }
941
942 static int
943 sig_digest (const char *option, int argc, char *argv[], void *cookie)
944 {
945   struct signinfo *si = cookie;
946   int i;
947   char *tail = NULL;
948
949   if (argc == 0)
950     log_fatal ("Usage: %s DIGEST_ALGO\n", option);
951
952   errno = 0;
953   i = strtoul (argv[0], &tail, 10);
954   if (errno || (tail && *tail))
955     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
956
957   si->digest_algo = i;
958
959   return 1;
960 }
961
962 static int
963 sig_timestamp (const char *option, int argc, char *argv[], void *cookie)
964 {
965   struct signinfo *si = cookie;
966   char *tail = NULL;
967
968   if (argc == 0)
969     log_fatal ("Usage: %s TIMESTAMP\n", option);
970
971   errno = 0;
972   si->timestamp = parse_timestamp (argv[0], &tail);
973   if (errno || (tail && *tail))
974     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
975
976   return 1;
977 }
978
979 static int
980 sig_expiration (const char *option, int argc, char *argv[], void *cookie)
981 {
982   struct signinfo *si = cookie;
983   int is_expiration = strcmp (option, "--expiration") == 0;
984   u32 *i = is_expiration ? &si->expiration : &si->key_expiration;
985
986   if (! is_expiration)
987     log_assert (strcmp (option, "--key-expiration") == 0);
988
989   if (argc == 0)
990     log_fatal ("Usage: %s DURATION\n", option);
991
992   *i = parse_expire_string (argv[0]);
993   if (*i == (u32)-1)
994     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
995
996   return 1;
997 }
998
999 static int
1000 sig_int_list (const char *option, int argc, char *argv[], void *cookie)
1001 {
1002   struct signinfo *si = cookie;
1003   int nvalues = 1;
1004   char *values = xmalloc (nvalues * sizeof (values[0]));
1005   char *tail = argv[0];
1006   int i;
1007   byte **a;
1008   int *n;
1009
1010   if (argc == 0)
1011     log_fatal ("Usage: %s VALUE[,VALUE...]\n", option);
1012
1013   for (i = 0; tail && *tail; i ++)
1014     {
1015       int v;
1016       char *old_tail = tail;
1017
1018       errno = 0;
1019       v = strtol (tail, &tail, 0);
1020       if (errno || old_tail == tail || (tail && !(*tail == ',' || *tail == 0)))
1021         log_fatal ("Invalid value passed to %s (%s).  "
1022                    "Expected a list of comma separated numbers\n",
1023                    option, argv[0]);
1024
1025       if (! (0 <= v && v <= 255))
1026         log_fatal ("%s: %d is out of range (Expected: 0-255)\n", option, v);
1027
1028       if (i == nvalues)
1029         {
1030           nvalues *= 2;
1031           values = xrealloc (values, nvalues * sizeof (values[0]));
1032         }
1033
1034       values[i] = v;
1035
1036       if (*tail == ',')
1037         tail ++;
1038       else
1039         log_assert (*tail == 0);
1040     }
1041
1042   if (strcmp ("--cipher-algos", option) == 0)
1043     {
1044       a = &si->cipher_algorithms;
1045       n = &si->cipher_algorithms_len;
1046     }
1047   else if (strcmp ("--digest-algos", option) == 0)
1048     {
1049       a = &si->digest_algorithms;
1050       n = &si->digest_algorithms_len;
1051     }
1052   else if (strcmp ("--compress-algos", option) == 0)
1053     {
1054       a = &si->compress_algorithms;
1055       n = &si->compress_algorithms_len;
1056     }
1057   else
1058     log_fatal ("Cannot handle %s\n", option);
1059
1060   if (*a)
1061     log_fatal ("Option %s given multiple times.\n", option);
1062
1063   *a = values;
1064   *n = i;
1065
1066   return 1;
1067 }
1068
1069 static int
1070 sig_flag (const char *option, int argc, char *argv[], void *cookie)
1071 {
1072   struct signinfo *si = cookie;
1073   int range[2] = {0, 255};
1074   char *tail;
1075   int v;
1076
1077   if (strcmp (option, "--primary-user-id") == 0)
1078     range[1] = 1;
1079
1080   if (argc <= 1)
1081     {
1082       if (range[0] == 0 && range[1] == 1)
1083         log_fatal ("Usage: %s 0|1\n", option);
1084       else
1085         log_fatal ("Usage: %s %d-%d\n", option, range[0], range[1]);
1086     }
1087
1088   errno = 0;
1089   v = strtol (argv[0], &tail, 0);
1090   if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1]))
1091     log_fatal ("Invalid value passed to %s (%s).  Expected %d-%d\n",
1092                option, argv[0], range[0], range[1]);
1093
1094   if (strcmp (option, "--exportable") == 0)
1095     {
1096       si->exportable_set = 1;
1097       si->exportable = v;
1098     }
1099   else if (strcmp (option, "--revocable") == 0)
1100     {
1101       si->revocable_set = 1;
1102       si->revocable = v;
1103     }
1104   else if (strcmp (option, "--primary-user-id") == 0)
1105     {
1106       si->primary_user_id_set = 1;
1107       si->primary_user_id = v;
1108     }
1109   else
1110     log_fatal ("Cannot handle %s\n", option);
1111
1112   return 1;
1113 }
1114
1115 static int
1116 sig_trust_level (const char *option, int argc, char *argv[], void *cookie)
1117 {
1118   struct signinfo *si = cookie;
1119   int i;
1120   char *tail;
1121
1122   if (argc <= 1)
1123     log_fatal ("Usage: %s DEPTH TRUST_AMOUNT\n", option);
1124
1125   for (i = 0; i < sizeof (si->trust_args) / sizeof (si->trust_args[0]); i ++)
1126     {
1127       int v;
1128
1129       errno = 0;
1130       v = strtol (argv[i], &tail, 0);
1131       if (errno || (tail && *tail) || !(0 <= v && v <= 255))
1132         log_fatal ("Invalid value passed to %s (%s).  Expected 0-255\n",
1133                    option, argv[i]);
1134
1135       si->trust_args[i] = v;
1136     }
1137
1138   si->trust_level_set = 1;
1139
1140   return 2;
1141 }
1142
1143 static int
1144 sig_string_arg (const char *option, int argc, char *argv[], void *cookie)
1145 {
1146   struct signinfo *si = cookie;
1147   char *p = argv[0];
1148   char **s;
1149
1150   if (argc == 0)
1151     log_fatal ("Usage: %s STRING\n", option);
1152
1153   if (strcmp (option, "--trust-scope") == 0)
1154     s = &si->trust_scope;
1155   else if (strcmp (option, "--key-server") == 0)
1156     s = &si->key_server;
1157   else if (strcmp (option, "--signers-user-id") == 0)
1158     s = &si->signers_user_id;
1159   else if (strcmp (option, "--policy-uri") == 0)
1160     s = &si->policy_uri;
1161   else
1162     log_fatal ("Cannot handle %s\n", option);
1163
1164   if (*s)
1165     log_fatal ("%s already given.\n", option);
1166
1167   *s = xstrdup (p);
1168
1169   return 1;
1170 }
1171
1172 static int
1173 sig_revocation_key (const char *option, int argc, char *argv[], void *cookie)
1174 {
1175   gpg_error_t err;
1176   struct signinfo *si = cookie;
1177   int v;
1178   char *tail;
1179   PKT_public_key pk;
1180   struct revocation_key *revkey;
1181
1182   if (argc < 2)
1183     log_fatal ("Usage: %s CLASS KEYID\n", option);
1184
1185   memset (&pk, 0, sizeof (pk));
1186
1187   errno = 0;
1188   v = strtol (argv[0], &tail, 16);
1189   if (errno || (tail && *tail) || !(0 <= v && v <= 255))
1190     log_fatal ("%s: Invalid class value (%s).  Expected 0-255\n",
1191                option, argv[0]);
1192
1193   pk.req_usage = PUBKEY_USAGE_SIG;
1194   err = get_pubkey_byname (NULL, NULL, &pk, argv[1], NULL, NULL, 1, 1);
1195   if (err)
1196     log_fatal ("looking up key %s: %s\n", argv[1], gpg_strerror (err));
1197
1198   si->nrevocation_keys ++;
1199   si->revocation_key = xrealloc (si->revocation_key,
1200                                  si->nrevocation_keys
1201                                  * sizeof (*si->revocation_key));
1202   revkey = &si->revocation_key[si->nrevocation_keys - 1];
1203
1204   revkey->class = v;
1205   revkey->algid = pk.pubkey_algo;
1206   fingerprint_from_pk (&pk, revkey->fpr, NULL);
1207
1208   release_public_key_parts (&pk);
1209
1210   return 2;
1211 }
1212
1213 static int
1214 sig_notation (const char *option, int argc, char *argv[], void *cookie)
1215 {
1216   struct signinfo *si = cookie;
1217   int is_blob = strcmp (option, "--notation") != 0;
1218   struct notation *notation;
1219   char *p = argv[0];
1220   int p_free = 0;
1221   char *data;
1222   int data_size;
1223   int data_len;
1224
1225   if (argc == 0)
1226     log_fatal ("Usage: %s [!<]name=value\n", option);
1227
1228   if ((p[0] == '!' && p[1] == '<') || p[0] == '<')
1229     /* Read from a file.  */
1230     {
1231       char *filename = NULL;
1232       iobuf_t in;
1233       int prefix;
1234
1235       if (p[0] == '<')
1236         p ++;
1237       else
1238         {
1239           /* Remove the '<', which string_to_notation does not
1240              understand, and preserve the '!'.  */
1241           p = xstrdup (&p[1]);
1242           p_free = 1;
1243           p[0] = '!';
1244         }
1245
1246       filename = strchr (p, '=');
1247       if (! filename)
1248         log_fatal ("No value specified.  Usage: %s [!<]name=value\n",
1249                    option);
1250       filename ++;
1251
1252       prefix = (size_t) filename - (size_t) p;
1253
1254       errno = 0;
1255       in = iobuf_open (filename);
1256       if (! in)
1257         log_fatal ("Opening '%s': %s\n",
1258                    filename, errno ? strerror (errno): "unknown error");
1259
1260       /* A notation can be at most about a few dozen bytes short of
1261          64k.  Since this is relatively small, we just allocate that
1262          much instead of trying to dynamically size a buffer.  */
1263       data_size = 64 * 1024;
1264       data = xmalloc (data_size);
1265       log_assert (prefix <= data_size);
1266       memcpy (data, p, prefix);
1267
1268       data_len = iobuf_read (in, &data[prefix], data_size - prefix - 1);
1269       if (data_len == -1)
1270         /* EOF => 0 bytes read.  */
1271         data_len = 0;
1272
1273       if (data_len == data_size - prefix - 1)
1274         /* Technically, we should do another read and check for EOF,
1275            but what's one byte more or less?  */
1276         log_fatal ("Notation data doesn't fit in the packet.\n");
1277
1278       iobuf_close (in);
1279
1280       /* NUL terminate it.  */
1281       data[prefix + data_len] = 0;
1282
1283       if (p_free)
1284         xfree (p);
1285       p = data;
1286       p_free = 1;
1287       data = &p[prefix];
1288
1289       if (is_blob)
1290         p[prefix - 1] = 0;
1291     }
1292   else if (is_blob)
1293     {
1294       data = strchr (p, '=');
1295       if (! data)
1296         {
1297           data = p;
1298           data_len = 0;
1299         }
1300       else
1301         {
1302           p = xstrdup (p);
1303           p_free = 1;
1304
1305           data = strchr (p, '=');
1306           log_assert (data);
1307
1308           /* NUL terminate the name.  */
1309           *data = 0;
1310           data ++;
1311           data_len = strlen (data);
1312         }
1313     }
1314
1315   if (is_blob)
1316     notation = blob_to_notation (p, data, data_len);
1317   else
1318     notation = string_to_notation (p, 1);
1319   if (! notation)
1320     log_fatal ("creating notation: an unknown error occurred.\n");
1321   notation->next = si->notations;
1322   si->notations = notation;
1323
1324   if (p_free)
1325     xfree (p);
1326
1327   return 1;
1328 }
1329
1330 static int
1331 sig_big_endian_arg (const char *option, int argc, char *argv[], void *cookie)
1332 {
1333   struct signinfo *si = cookie;
1334   char *p = argv[0];
1335   int i;
1336   int l;
1337   char *bytes;
1338
1339   if (argc == 0)
1340     log_fatal ("Usage: %s HEXDIGITS\n", option);
1341
1342   /* Skip a leading "0x".  */
1343   if (p[0] == '0' && p[1] == 'x')
1344     p += 2;
1345
1346   for (i = 0; i < strlen (p); i ++)
1347     if (!hexdigitp (&p[i]))
1348       log_fatal ("%s: argument ('%s') must consist of hex digits.\n",
1349                  option, p);
1350   if (strlen (p) % 2 != 0)
1351       log_fatal ("%s: argument ('%s') must contain an even number of hex digits.\n",
1352                  option, p);
1353
1354   l = strlen (p) / 2;
1355   bytes = xmalloc (l);
1356   hex2bin (p, bytes, l);
1357
1358   if (strcmp (option, "--key-server-preferences") == 0)
1359     {
1360       if (si->key_server_preferences)
1361         log_fatal ("%s given multiple times.\n", option);
1362       si->key_server_preferences = bytes;
1363       si->key_server_preferences_len = l;
1364     }
1365   else if (strcmp (option, "--key-flags") == 0)
1366     {
1367       if (si->key_flags)
1368         log_fatal ("%s given multiple times.\n", option);
1369       si->key_flags = bytes;
1370       si->key_flags_len = l;
1371     }
1372   else if (strcmp (option, "--features") == 0)
1373     {
1374       if (si->features)
1375         log_fatal ("%s given multiple times.\n", option);
1376       si->features = bytes;
1377       si->features_len = l;
1378     }
1379   else
1380     log_fatal ("Cannot handle %s\n", option);
1381
1382   return 1;
1383 }
1384
1385 static int
1386 sig_reason_for_revocation (const char *option, int argc, char *argv[], void *cookie)
1387 {
1388   struct signinfo *si = cookie;
1389   int v;
1390   char *tail;
1391
1392   if (argc < 2)
1393     log_fatal ("Usage: %s REASON_CODE REASON_STRING\n", option);
1394
1395   errno = 0;
1396   v = strtol (argv[0], &tail, 16);
1397   if (errno || (tail && *tail) || !(0 <= v && v <= 255))
1398     log_fatal ("%s: Invalid reason code (%s).  Expected 0-255\n",
1399                option, argv[0]);
1400
1401   if (si->reason_for_revocation)
1402     log_fatal ("%s given multiple times.\n", option);
1403
1404   si->reason_for_revocation_code = v;
1405   si->reason_for_revocation = xstrdup (argv[1]);
1406
1407   return 2;
1408 }
1409
1410 static int
1411 sig_corrupt (const char *option, int argc, char *argv[], void *cookie)
1412 {
1413   struct signinfo *si = cookie;
1414
1415   (void) option;
1416   (void) argc;
1417   (void) argv;
1418   (void) cookie;
1419
1420   si->corrupt = 1;
1421
1422   return 0;
1423 }
1424
1425 static struct option sig_options[] = {
1426   { "--issuer", sig_issuer,
1427     "The key to use to generate the signature."},
1428   { "--issuer-keyid", sig_issuer_keyid,
1429     "Set the issuer's key id.  This is useful for creating a "
1430     "self-signature.  As a special case, the value \"self\" refers "
1431     "to the primary key's key id.  "
1432     "(RFC 4880, Section 5.2.3.5)" },
1433   { "--pk", sig_pk,
1434     "The primary keyas an index into the components (keys and uids) "
1435     "created so far where the first component has the index 0." },
1436   { "--sk", sig_pk,
1437     "The subkey as an index into the components (keys and uids) created "
1438     "so far where the first component has the index 0.  Only needed for "
1439     "0x18, 0x19, and 0x28 signatures." },
1440   { "--user-id", sig_user_id,
1441     "The user id as an index into the components (keys and uids) created "
1442     "so far where the first component has the index 0.  Only needed for "
1443     "0x10-0x13 and 0x30 signatures." },
1444   { "--class", sig_class,
1445     "The signature's class.  Valid values are "
1446     "0x10-0x13 (user id and primary-key certification), "
1447     "0x18 (subkey binding), "
1448     "0x19 (primary key binding), "
1449     "0x1f (direct primary key signature), "
1450     "0x20 (key revocation), "
1451     "0x28 (subkey revocation), and "
1452     "0x30 (certification revocation)."
1453   },
1454   { "--digest", sig_digest, "The digest algorithm" },
1455   { "--timestamp", sig_timestamp,
1456     "The signature's creation time.  " TIMESTAMP_HELP "  0 means now.  "
1457     "(RFC 4880, Section 5.2.3.4)" },
1458   { "--key-expiration", sig_expiration,
1459     "The number of days until the associated key expires.  To specify "
1460     "seconds, prefix the value with \"seconds=\".  It is also possible "
1461     "to use 'y', 'm' and 'w' as simple multipliers.  For instance, 2y "
1462     "means 2 years, etc.  "
1463     "(RFC 4880, Section 5.2.3.6)" },
1464   { "--cipher-algos", sig_int_list,
1465     "A comma separated list of the preferred cipher algorithms (identified by "
1466     "their number, see RFC 4880, Section 9).  "
1467     "(RFC 4880, Section 5.2.3.7)" },
1468   { "--digest-algos", sig_int_list,
1469     "A comma separated list of the preferred algorithms (identified by "
1470     "their number, see RFC 4880, Section 9).  "
1471     "(RFC 4880, Section 5.2.3.8)" },
1472   { "--compress-algos", sig_int_list,
1473     "A comma separated list of the preferred algorithms (identified by "
1474     "their number, see RFC 4880, Section 9)."
1475     "(RFC 4880, Section 5.2.3.9)" },
1476   { "--expiration", sig_expiration,
1477     "The number of days until the signature expires.  To specify seconds, "
1478     "prefix the value with \"seconds=\".  It is also possible to use 'y', "
1479     "'m' and 'w' as simple multipliers.  For instance, 2y means 2 years, "
1480     "etc.  "
1481     "(RFC 4880, Section 5.2.3.10)" },
1482   { "--exportable", sig_flag,
1483     "Mark this signature as exportable (1) or local (0).  "
1484     "(RFC 4880, Section 5.2.3.11)" },
1485   { "--revocable", sig_flag,
1486     "Mark this signature as revocable (1, revocations are ignored) "
1487     "or non-revocable (0).  "
1488     "(RFC 4880, Section 5.2.3.12)" },
1489   { "--trust-level", sig_trust_level,
1490     "Set the trust level.  This takes two integer arguments (0-255): "
1491     "the trusted-introducer level and the degree of trust.  "
1492     "(RFC 4880, Section 5.2.3.13.)" },
1493   { "--trust-scope", sig_string_arg,
1494     "A regular expression that limits the scope of --trust-level.  "
1495     "(RFC 4880, Section 5.2.3.14.)" },
1496   { "--revocation-key", sig_revocation_key,
1497     "Specify a designated revoker.  Takes two arguments: the class "
1498     "(normally 0x80 or 0xC0 (sensitive)) and the key id of the "
1499     "designatured revoker.  May be given multiple times.  "
1500     "(RFC 4880, Section 5.2.3.15)" },
1501   { "--notation", sig_notation,
1502     "Add a human-readable notation of the form \"[!<]name=value\" where "
1503     "\"!\" means that the critical flag should be set and \"<\" means "
1504     "that VALUE is a file to read the data from.  "
1505     "(RFC 4880, Section 5.2.3.16)" },
1506   { "--notation-binary", sig_notation,
1507     "Add a binary notation of the form \"[!<]name=value\" where "
1508     "\"!\" means that the critical flag should be set and \"<\" means "
1509     "that VALUE is a file to read the data from.  "
1510     "(RFC 4880, Section 5.2.3.16)" },
1511   { "--key-server-preferences", sig_big_endian_arg,
1512     "Big-endian number encoding the keyserver preferences. "
1513     "(RFC 4880, Section 5.2.3.17)" },
1514   { "--key-server", sig_string_arg,
1515     "The preferred keyserver.  (RFC 4880, Section 5.2.3.18)" },
1516   { "--primary-user-id", sig_flag,
1517     "Sets the primary user id flag.  (RFC 4880, Section 5.2.3.19)" },
1518   { "--policy-uri", sig_string_arg,
1519     "URI of a document that describes the issuer's signing policy.  "
1520     "(RFC 4880, Section 5.2.3.20)" },
1521   { "--key-flags", sig_big_endian_arg,
1522     "Big-endian number encoding the key flags. "
1523     "(RFC 4880, Section 5.2.3.21)" },
1524   { "--signers-user-id", sig_string_arg,
1525     "The user id (as a string) responsible for the signing.  "
1526     "(RFC 4880, Section 5.2.3.22)" },
1527   { "--reason-for-revocation", sig_reason_for_revocation,
1528     "Takes two arguments: a reason for revocation code and a "
1529     "user-provided string.  "
1530     "(RFC 4880, Section 5.2.3.23)" },
1531   { "--features", sig_big_endian_arg,
1532     "Big-endian number encoding the feature flags. "
1533     "(RFC 4880, Section 5.2.3.24)" },
1534   { "--signature-target", NULL,
1535     "Takes three arguments: the target signature's public key algorithm "
1536     " (as an integer), the hash algorithm (as an integer) and the hash "
1537     " (as a hexadecimal string).  "
1538     "(RFC 4880, Section 5.2.3.25)" },
1539   { "--embedded-signature", NULL,
1540     "An embedded signature.  This must be immediately followed by a "
1541     "signature packet (created using --signature ...) or a filename "
1542     "containing the packet."
1543     "(RFC 4880, Section 5.2.3.26)" },
1544   { "--hashed", NULL,
1545     "The following attributes will be placed in the hashed area of "
1546     "the signature.  (This is the default and it reset at the end of"
1547     "each signature.)" },
1548   { "--unhashed", NULL,
1549     "The following attributes will be placed in the unhashed area of "
1550     "the signature (and thus not integrity protected)." },
1551   { "--corrupt", sig_corrupt,
1552     "Corrupt the signature." },
1553   { NULL, NULL,
1554     "Example:\n\n"
1555     "  $ gpgcompose --public-key $KEYID --user-id USERID \\\n"
1556     "  --signature --class 0x10 --issuer $KEYID --issuer-keyid self \\\n"
1557     "  | " GPG_NAME " --list-packets"}
1558 };
1559
1560 static int
1561 mksubpkt_callback (PKT_signature *sig, void *cookie)
1562 {
1563   struct signinfo *si = cookie;
1564   int i;
1565
1566   if (si->key_expiration)
1567     {
1568       char buf[4];
1569       buf[0] = (si->key_expiration >> 24) & 0xff;
1570       buf[1] = (si->key_expiration >> 16) & 0xff;
1571       buf[2] = (si->key_expiration >>  8) & 0xff;
1572       buf[3] = si->key_expiration & 0xff;
1573       build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
1574     }
1575
1576   if (si->cipher_algorithms)
1577     build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM,
1578                       si->cipher_algorithms,
1579                       si->cipher_algorithms_len);
1580
1581   if (si->digest_algorithms)
1582     build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH,
1583                       si->digest_algorithms,
1584                       si->digest_algorithms_len);
1585
1586   if (si->compress_algorithms)
1587     build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR,
1588                       si->compress_algorithms,
1589                       si->compress_algorithms_len);
1590
1591   if (si->exportable_set)
1592     {
1593       char buf = si->exportable;
1594       build_sig_subpkt (sig, SIGSUBPKT_EXPORTABLE, &buf, 1);
1595     }
1596
1597   if (si->trust_level_set)
1598     build_sig_subpkt (sig, SIGSUBPKT_TRUST,
1599                       si->trust_args, sizeof (si->trust_args));
1600
1601   if (si->trust_scope)
1602     build_sig_subpkt (sig, SIGSUBPKT_REGEXP,
1603                       si->trust_scope, strlen (si->trust_scope));
1604
1605   for (i = 0; i < si->nrevocation_keys; i ++)
1606     {
1607       struct revocation_key *revkey = &si->revocation_key[i];
1608       gpg_error_t err = keygen_add_revkey (sig, revkey);
1609       if (err)
1610         {
1611           u32 keyid[2];
1612           keyid_from_fingerprint (revkey->fpr, 20, keyid);
1613           log_fatal ("adding revocation key %s: %s\n",
1614                      keystr (keyid), gpg_strerror (err));
1615         }
1616     }
1617
1618   /* keygen_add_revkey sets revocable=0 so be sure to do this after
1619      adding the rev keys.  */
1620   if (si->revocable_set)
1621     {
1622       char buf = si->revocable;
1623       build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, &buf, 1);
1624     }
1625
1626   keygen_add_notations (sig, si->notations);
1627
1628   if (si->key_server_preferences)
1629     build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS,
1630                       si->key_server_preferences,
1631                       si->key_server_preferences_len);
1632
1633   if (si->key_server)
1634     build_sig_subpkt (sig, SIGSUBPKT_PREF_KS,
1635                       si->key_server, strlen (si->key_server));
1636
1637   if (si->primary_user_id_set)
1638     {
1639       char buf = si->primary_user_id;
1640       build_sig_subpkt (sig, SIGSUBPKT_PRIMARY_UID, &buf, 1);
1641     }
1642
1643   if (si->policy_uri)
1644     build_sig_subpkt (sig, SIGSUBPKT_POLICY,
1645                       si->policy_uri, strlen (si->policy_uri));
1646
1647   if (si->key_flags)
1648     build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS,
1649                       si->key_flags, si->key_flags_len);
1650
1651   if (si->signers_user_id)
1652     build_sig_subpkt (sig, SIGSUBPKT_SIGNERS_UID,
1653                       si->signers_user_id, strlen (si->signers_user_id));
1654
1655   if (si->reason_for_revocation)
1656     {
1657       int len = 1 + strlen (si->reason_for_revocation);
1658       char *buf;
1659
1660       buf = xmalloc (len);
1661
1662       buf[0] = si->reason_for_revocation_code;
1663       memcpy (&buf[1], si->reason_for_revocation, len - 1);
1664
1665       build_sig_subpkt (sig, SIGSUBPKT_REVOC_REASON, buf, len);
1666
1667       xfree (buf);
1668     }
1669
1670   if (si->features)
1671     build_sig_subpkt (sig, SIGSUBPKT_FEATURES,
1672                       si->features, si->features_len);
1673
1674   return 0;
1675 }
1676
1677 static int
1678 signature (const char *option, int argc, char *argv[], void *cookie)
1679 {
1680   gpg_error_t err;
1681   iobuf_t out = cookie;
1682   struct signinfo si;
1683   int processed;
1684   PKT_public_key *pk;
1685   PKT_signature *sig;
1686   PACKET pkt;
1687   u32 keyid_orig[2], keyid[2];
1688
1689   (void) option;
1690
1691   memset (&si, 0, sizeof (si));
1692   memset (&pkt, 0, sizeof (pkt));
1693
1694   processed = process_options (option,
1695                                major_options,
1696                                sig_options, &si,
1697                                global_options, NULL,
1698                                argc, argv);
1699
1700   if (ncomponents)
1701     {
1702       int pkttype = components[ncomponents - 1].pkttype;
1703
1704       if (pkttype == PKT_PUBLIC_KEY)
1705         {
1706           if (! si.class)
1707             /* Direct key sig.  */
1708             si.class = 0x1F;
1709         }
1710       else if (pkttype == PKT_PUBLIC_SUBKEY)
1711         {
1712           if (! si.sk)
1713             si.sk = components[ncomponents - 1].pkt.public_key;
1714           if (! si.class)
1715             /* Subkey binding sig.  */
1716             si.class = 0x18;
1717         }
1718       else if (pkttype == PKT_USER_ID)
1719         {
1720           if (! si.uid)
1721             si.uid = components[ncomponents - 1].pkt.user_id;
1722           if (! si.class)
1723             /* Certification of a user id and public key packet.  */
1724             si.class = 0x10;
1725         }
1726     }
1727
1728   pk = NULL;
1729   if (! si.pk || ! si.issuer_pk)
1730     /* No primary key specified.  Default to the first one that we
1731        find.  */
1732     {
1733       int i;
1734       for (i = 0; i < ncomponents; i ++)
1735         if (components[i].pkttype == PKT_PUBLIC_KEY)
1736           {
1737             pk = components[i].pkt.public_key;
1738             break;
1739           }
1740     }
1741
1742   if (! si.pk)
1743     {
1744       if (! pk)
1745         log_fatal ("%s: no primary key given and no primary key available",
1746                    "--pk");
1747       si.pk = pk;
1748     }
1749   if (! si.issuer_pk)
1750     {
1751       if (! pk)
1752         log_fatal ("%s: no issuer key given and no primary key available",
1753                    "--issuer");
1754       si.issuer_pk = pk;
1755     }
1756
1757   if (si.class == 0x18 || si.class == 0x19 || si.class == 0x28)
1758     /* Requires the primary key and a subkey.  */
1759     {
1760       if (! si.sk)
1761         log_fatal ("sig class 0x%x requires a subkey (--sk)\n", si.class);
1762     }
1763   else if (si.class == 0x10
1764            || si.class == 0x11
1765            || si.class == 0x12
1766            || si.class == 0x13
1767            || si.class == 0x30)
1768     /* Requires the primary key and a user id.  */
1769     {
1770       if (! si.uid)
1771         log_fatal ("sig class 0x%x requires a uid (--uid)\n", si.class);
1772     }
1773   else if (si.class == 0x1F || si.class == 0x20)
1774     /* Just requires the primary key.  */
1775     ;
1776   else
1777     log_fatal ("Unsupported signature class: 0x%x\n", si.class);
1778
1779   sig = xmalloc_clear (sizeof (*sig));
1780
1781   /* Save SI.ISSUER_PK->KEYID.  */
1782   keyid_copy (keyid_orig, pk_keyid (si.issuer_pk));
1783   if (si.issuer_keyid[0] || si.issuer_keyid[1])
1784     keyid_copy (si.issuer_pk->keyid, si.issuer_keyid);
1785   else if (si.issuer_keyid_self)
1786     {
1787       PKT_public_key *pripk = primary_key();
1788       if (! pripk)
1789         log_fatal ("--issuer-keyid self given, but no primary key available.\n");
1790       keyid_copy (si.issuer_pk->keyid, pk_keyid (pripk));
1791     }
1792
1793   /* Changing the issuer's key id is fragile.  Check to make sure
1794      make_keysig_packet didn't recompute the keyid.  */
1795   keyid_copy (keyid, si.issuer_pk->keyid);
1796   err = make_keysig_packet (&sig, si.pk, si.uid, si.sk, si.issuer_pk,
1797                             si.class, si.digest_algo,
1798                             si.timestamp, si.expiration,
1799                             mksubpkt_callback, &si, NULL);
1800   log_assert (keyid_cmp (keyid, si.issuer_pk->keyid) == 0);
1801   if (err)
1802     log_fatal ("Generating signature: %s\n", gpg_strerror (err));
1803
1804   /* Restore SI.PK->KEYID.  */
1805   keyid_copy (si.issuer_pk->keyid, keyid_orig);
1806
1807   if (si.corrupt)
1808     {
1809       /* Set the top 32-bits to 0xBAD0DEAD.  */
1810       int bits = gcry_mpi_get_nbits (sig->data[0]);
1811       gcry_mpi_t x = gcry_mpi_new (0);
1812       gcry_mpi_add_ui (x, x, 0xBAD0DEAD);
1813       gcry_mpi_lshift (x, x, bits > 32 ? bits - 32 : bits);
1814       gcry_mpi_clear_highbit (sig->data[0], bits > 32 ? bits - 32 : 0);
1815       gcry_mpi_add (sig->data[0], sig->data[0], x);
1816       gcry_mpi_release (x);
1817     }
1818
1819   pkt.pkttype = PKT_SIGNATURE;
1820   pkt.pkt.signature = sig;
1821
1822   err = build_packet (out, &pkt);
1823   if (err)
1824     log_fatal ("serializing public key packet: %s\n", gpg_strerror (err));
1825
1826   debug ("Wrote signature packet:\n");
1827   dump_component (&pkt);
1828
1829   xfree (sig);
1830   release_kbnode (si.issuer_kb);
1831   xfree (si.revocation_key);
1832
1833   return processed;
1834 }
1835 \f
1836 struct sk_esk_info
1837 {
1838   /* The cipher used for encrypting the session key (when a session
1839      key is used).  */
1840   int cipher;
1841   /* The cipher used for encryping the SED packet.  */
1842   int sed_cipher;
1843
1844   /* S2K related data.  */
1845   int hash;
1846   int mode;
1847   int mode_set;
1848   byte salt[8];
1849   int salt_set;
1850   int iterations;
1851
1852   /* If applying the S2K function to the passphrase is the session key
1853      or if it is the decryption key for the session key.  */
1854   int s2k_is_session_key;
1855   /* Generate a new, random session key.  */
1856   int new_session_key;
1857
1858   /* The unencrypted session key.  */
1859   int session_key_len;
1860   char *session_key;
1861
1862   char *password;
1863 };
1864
1865 static int
1866 sk_esk_cipher (const char *option, int argc, char *argv[], void *cookie)
1867 {
1868   struct sk_esk_info *si = cookie;
1869   char *usage = "integer|IDEA|3DES|CAST5|BLOWFISH|AES|AES192|AES256|CAMELLIA128|CAMELLIA192|CAMELLIA256";
1870   int cipher;
1871
1872   if (argc == 0)
1873     log_fatal ("Usage: %s %s\n", option, usage);
1874
1875   if (strcasecmp (argv[0], "IDEA") == 0)
1876     cipher = CIPHER_ALGO_IDEA;
1877   else if (strcasecmp (argv[0], "3DES") == 0)
1878     cipher = CIPHER_ALGO_3DES;
1879   else if (strcasecmp (argv[0], "CAST5") == 0)
1880     cipher = CIPHER_ALGO_CAST5;
1881   else if (strcasecmp (argv[0], "BLOWFISH") == 0)
1882     cipher = CIPHER_ALGO_BLOWFISH;
1883   else if (strcasecmp (argv[0], "AES") == 0)
1884     cipher = CIPHER_ALGO_AES;
1885   else if (strcasecmp (argv[0], "AES192") == 0)
1886     cipher = CIPHER_ALGO_AES192;
1887   else if (strcasecmp (argv[0], "TWOFISH") == 0)
1888     cipher = CIPHER_ALGO_TWOFISH;
1889   else if (strcasecmp (argv[0], "CAMELLIA128") == 0)
1890     cipher = CIPHER_ALGO_CAMELLIA128;
1891   else if (strcasecmp (argv[0], "CAMELLIA192") == 0)
1892     cipher = CIPHER_ALGO_CAMELLIA192;
1893   else if (strcasecmp (argv[0], "CAMELLIA256") == 0)
1894     cipher = CIPHER_ALGO_CAMELLIA256;
1895   else
1896     {
1897       char *tail;
1898       int v;
1899
1900       errno = 0;
1901       v = strtol (argv[0], &tail, 0);
1902       if (errno || (tail && *tail) || ! valid_cipher (v))
1903         log_fatal ("Invalid or unsupported value.  Usage: %s %s\n",
1904                    option, usage);
1905
1906       cipher = v;
1907     }
1908
1909   if (strcmp (option, "--cipher") == 0)
1910     {
1911       if (si->cipher)
1912         log_fatal ("%s given multiple times.", option);
1913       si->cipher = cipher;
1914     }
1915   else if (strcmp (option, "--sed-cipher") == 0)
1916     {
1917       if (si->sed_cipher)
1918         log_fatal ("%s given multiple times.", option);
1919       si->sed_cipher = cipher;
1920     }
1921
1922   return 1;
1923 }
1924
1925 static int
1926 sk_esk_mode (const char *option, int argc, char *argv[], void *cookie)
1927 {
1928   struct sk_esk_info *si = cookie;
1929   char *usage = "integer|simple|salted|iterated";
1930
1931   if (argc == 0)
1932     log_fatal ("Usage: %s %s\n", option, usage);
1933
1934   if (si->mode)
1935     log_fatal ("%s given multiple times.", option);
1936
1937   if (strcasecmp (argv[0], "simple") == 0)
1938     si->mode = 0;
1939   else if (strcasecmp (argv[0], "salted") == 0)
1940     si->mode = 1;
1941   else if (strcasecmp (argv[0], "iterated") == 0)
1942     si->mode = 3;
1943   else
1944     {
1945       char *tail;
1946       int v;
1947
1948       errno = 0;
1949       v = strtol (argv[0], &tail, 0);
1950       if (errno || (tail && *tail) || ! (v == 0 || v == 1 || v == 3))
1951         log_fatal ("Invalid or unsupported value.  Usage: %s %s\n",
1952                    option, usage);
1953
1954       si->mode = v;
1955     }
1956
1957   si->mode_set = 1;
1958
1959   return 1;
1960 }
1961
1962 static int
1963 sk_esk_hash_algorithm (const char *option, int argc, char *argv[], void *cookie)
1964 {
1965   struct sk_esk_info *si = cookie;
1966   char *usage = "integer|MD5|SHA1|RMD160|SHA256|SHA384|SHA512|SHA224";
1967
1968   if (argc == 0)
1969     log_fatal ("Usage: %s %s\n", option, usage);
1970
1971   if (si->hash)
1972     log_fatal ("%s given multiple times.", option);
1973
1974   if (strcasecmp (argv[0], "MD5") == 0)
1975     si->hash = DIGEST_ALGO_MD5;
1976   else if (strcasecmp (argv[0], "SHA1") == 0)
1977     si->hash = DIGEST_ALGO_SHA1;
1978   else if (strcasecmp (argv[0], "RMD160") == 0)
1979     si->hash = DIGEST_ALGO_RMD160;
1980   else if (strcasecmp (argv[0], "SHA256") == 0)
1981     si->hash = DIGEST_ALGO_SHA256;
1982   else if (strcasecmp (argv[0], "SHA384") == 0)
1983     si->hash = DIGEST_ALGO_SHA384;
1984   else if (strcasecmp (argv[0], "SHA512") == 0)
1985     si->hash = DIGEST_ALGO_SHA512;
1986   else if (strcasecmp (argv[0], "SHA224") == 0)
1987     si->hash = DIGEST_ALGO_SHA224;
1988   else
1989     {
1990       char *tail;
1991       int v;
1992
1993       errno = 0;
1994       v = strtol (argv[0], &tail, 0);
1995       if (errno || (tail && *tail)
1996           || ! (v == DIGEST_ALGO_MD5
1997                 || v == DIGEST_ALGO_SHA1
1998                 || v == DIGEST_ALGO_RMD160
1999                 || v == DIGEST_ALGO_SHA256
2000                 || v == DIGEST_ALGO_SHA384
2001                 || v == DIGEST_ALGO_SHA512
2002                 || v == DIGEST_ALGO_SHA224))
2003         log_fatal ("Invalid or unsupported value.  Usage: %s %s\n",
2004                    option, usage);
2005
2006       si->hash = v;
2007     }
2008
2009   return 1;
2010 }
2011
2012 static int
2013 sk_esk_salt (const char *option, int argc, char *argv[], void *cookie)
2014 {
2015   struct sk_esk_info *si = cookie;
2016   char *usage = "16-HEX-CHARACTERS";
2017   char *p = argv[0];
2018
2019   if (argc == 0)
2020     log_fatal ("Usage: %s %s\n", option, usage);
2021
2022   if (si->salt_set)
2023     log_fatal ("%s given multiple times.", option);
2024
2025   if (p[0] == '0' && p[1] == 'x')
2026     p += 2;
2027
2028   if (strlen (p) != 16)
2029     log_fatal ("%s: Salt must be exactly 16 hexadecimal characters (have: %zd)\n",
2030                option, strlen (p));
2031
2032   if (hex2bin (p, si->salt, sizeof (si->salt)) == -1)
2033     log_fatal ("%s: Salt must only contain hexadecimal characters\n",
2034                option);
2035
2036   si->salt_set = 1;
2037
2038   return 1;
2039 }
2040
2041 static int
2042 sk_esk_iterations (const char *option, int argc, char *argv[], void *cookie)
2043 {
2044   struct sk_esk_info *si = cookie;
2045   char *usage = "ITERATION-COUNT";
2046   char *tail;
2047   int v;
2048
2049   if (argc == 0)
2050     log_fatal ("Usage: %s %s\n", option, usage);
2051
2052   errno = 0;
2053   v = strtol (argv[0], &tail, 0);
2054   if (errno || (tail && *tail) || v < 0)
2055     log_fatal ("%s: Non-negative integer expected.\n", option);
2056
2057   si->iterations = v;
2058
2059   return 1;
2060 }
2061
2062 static int
2063 sk_esk_session_key (const char *option, int argc, char *argv[], void *cookie)
2064 {
2065   struct sk_esk_info *si = cookie;
2066   char *usage = "HEX-CHARACTERS|auto|none";
2067   char *p = argv[0];
2068   struct session_key sk;
2069
2070   if (argc == 0)
2071     log_fatal ("Usage: %s %s\n", option, usage);
2072
2073   if (si->session_key || si->s2k_is_session_key
2074       || si->new_session_key)
2075     log_fatal ("%s given multiple times.", option);
2076
2077   if (strcasecmp (p, "none") == 0)
2078     {
2079       si->s2k_is_session_key = 1;
2080       return 1;
2081     }
2082   if (strcasecmp (p, "new") == 0)
2083     {
2084       si->new_session_key = 1;
2085       return 1;
2086     }
2087   if (strcasecmp (p, "auto") == 0)
2088     return 1;
2089
2090   sk = parse_session_key (option, p, 0);
2091
2092   if (si->session_key)
2093     log_fatal ("%s given multiple times.", option);
2094
2095   if (sk.algo)
2096     si->sed_cipher = sk.algo;
2097
2098   si->session_key_len = sk.keylen;
2099   si->session_key = sk.key;
2100
2101   return 1;
2102 }
2103
2104 static int
2105 sk_esk_password (const char *option, int argc, char *argv[], void *cookie)
2106 {
2107   struct sk_esk_info *si = cookie;
2108   char *usage = "PASSWORD";
2109
2110   if (argc == 0)
2111     log_fatal ("Usage: --sk-esk %s\n", usage);
2112
2113   if (si->password)
2114     log_fatal ("%s given multiple times.", option);
2115
2116   si->password = xstrdup (argv[0]);
2117
2118   return 1;
2119 }
2120
2121 static struct option sk_esk_options[] = {
2122   { "--cipher", sk_esk_cipher,
2123     "The encryption algorithm for encrypting the session key.  "
2124     "One of IDEA, 3DES, CAST5, BLOWFISH, AES (default), AES192, "
2125     "AES256, TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." },
2126   { "--sed-cipher", sk_esk_cipher,
2127     "The encryption algorithm for encrypting the SED packet.  "
2128     "One of IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, "
2129     "AES256 (default), TWOFISH, CAMELLIA128, CAMELLIA192, or CAMELLIA256." },
2130   { "--mode", sk_esk_mode,
2131     "The S2K mode.  Either one of the strings \"simple\", \"salted\" "
2132     "or \"iterated\" or an integer." },
2133   { "--hash", sk_esk_hash_algorithm,
2134     "The hash algorithm to used to derive the key.  One of "
2135     "MD5, SHA1 (default), RMD160, SHA256, SHA384, SHA512, or SHA224." },
2136   { "--salt", sk_esk_salt,
2137     "The S2K salt encoded as 16 hexadecimal characters.  One needed "
2138     "if the S2K function is in salted or iterated mode." },
2139   { "--iterations", sk_esk_iterations,
2140     "The iteration count.  If not provided, a reasonable value is chosen.  "
2141     "Note: due to the encoding scheme, not every value is valid.  For "
2142     "convenience, the provided value will be rounded appropriately.  "
2143     "Only needed if the S2K function is in iterated mode." },
2144   { "--session-key", sk_esk_session_key,
2145     "The session key to be encrypted by the S2K function as a hexadecimal "
2146     "string.  If this is \"new\", then a new session key is generated."
2147     "If this is \"auto\", then either the last session key is "
2148     "used, if the was none, one is generated.  If this is \"none\", then "
2149     "the session key is the result of applying the S2K algorithms to the "
2150     "password.  The session key may be prefaced with an integer and a colon "
2151     "to indicate the cipher to use for the SED packet (making --sed-cipher "
2152     "unnecessary and allowing the direct use of the result of "
2153     "\"" GPG_NAME " --show-session-key\")." },
2154   { "", sk_esk_password, "The password." },
2155   { NULL, NULL,
2156     "Example:\n\n"
2157     "  $ gpgcompose --sk-esk foobar --encrypted \\\n"
2158     "  --literal --value foo | " GPG_NAME " --list-packets" }
2159 };
2160
2161 static int
2162 sk_esk (const char *option, int argc, char *argv[], void *cookie)
2163 {
2164   iobuf_t out = cookie;
2165   gpg_error_t err;
2166   int processed;
2167   struct sk_esk_info si;
2168   DEK sesdek;
2169   DEK s2kdek;
2170   PKT_symkey_enc *ske;
2171   PACKET pkt;
2172
2173   memset (&si, 0, sizeof (si));
2174
2175   processed = process_options (option,
2176                                major_options,
2177                                sk_esk_options, &si,
2178                                global_options, NULL,
2179                                argc, argv);
2180
2181   if (! si.password)
2182     log_fatal ("%s: missing password.  Usage: %s PASSWORD", option, option);
2183
2184   /* Fill in defaults, if appropriate.  */
2185   if (! si.cipher)
2186     si.cipher = CIPHER_ALGO_AES;
2187
2188   if (! si.sed_cipher)
2189     si.sed_cipher = CIPHER_ALGO_AES256;
2190
2191   if (! si.hash)
2192     si.hash = DIGEST_ALGO_SHA1;
2193
2194   if (! si.mode_set)
2195     /* Salted and iterated.  */
2196     si.mode = 3;
2197
2198   if (si.mode != 0 && ! si.salt_set)
2199     /* Generate a salt.  */
2200     gcry_randomize (si.salt, 8, GCRY_STRONG_RANDOM);
2201
2202   if (si.mode == 0)
2203     {
2204       if (si.iterations)
2205         log_info ("%s: --iterations provided, but not used for mode=0\n",
2206                   option);
2207       si.iterations = 0;
2208     }
2209   else if (! si.iterations)
2210     si.iterations = 10000;
2211
2212   memset (&sesdek, 0, sizeof (sesdek));
2213   /* The session key is used to encrypt the SED packet.  */
2214   sesdek.algo = si.sed_cipher;
2215   if (si.session_key)
2216     /* Copy the unencrypted session key into SESDEK.  */
2217     {
2218       sesdek.keylen = openpgp_cipher_get_algo_keylen (sesdek.algo);
2219       if (sesdek.keylen != si.session_key_len)
2220         log_fatal ("%s: Cipher algorithm requires a %d byte session key, but provided session key is %d bytes.",
2221                    option, sesdek.keylen, si.session_key_len);
2222
2223       log_assert (sesdek.keylen <= sizeof (sesdek.key));
2224       memcpy (sesdek.key, si.session_key, sesdek.keylen);
2225     }
2226   else if (! si.s2k_is_session_key || si.new_session_key)
2227     /* We need a session key, but one wasn't provided.  Generate it.  */
2228     make_session_key (&sesdek);
2229
2230   /* The encrypted session key needs 1 + SESDEK.KEYLEN bytes of
2231      space.  */
2232   ske = xmalloc_clear (sizeof (*ske) + sesdek.keylen);
2233
2234   ske->version = 4;
2235   ske->cipher_algo = si.cipher;
2236
2237   ske->s2k.mode = si.mode;
2238   ske->s2k.hash_algo = si.hash;
2239   log_assert (sizeof (si.salt) == sizeof (ske->s2k.salt));
2240   memcpy (ske->s2k.salt, si.salt, sizeof (ske->s2k.salt));
2241   if (! si.s2k_is_session_key)
2242     /* 0 means get the default.  */
2243     ske->s2k.count = encode_s2k_iterations (si.iterations);
2244
2245
2246   /* Derive the symmetric key that is either the session key or the
2247      key used to encrypt the session key.  */
2248   memset (&s2kdek, 0, sizeof (s2kdek));
2249
2250   s2kdek.algo = si.cipher;
2251   s2kdek.keylen = openpgp_cipher_get_algo_keylen (s2kdek.algo);
2252
2253   err = gcry_kdf_derive (si.password, strlen (si.password),
2254                          ske->s2k.mode == 3 ? GCRY_KDF_ITERSALTED_S2K
2255                          : ske->s2k.mode == 1 ? GCRY_KDF_SALTED_S2K
2256                          : GCRY_KDF_SIMPLE_S2K,
2257                          ske->s2k.hash_algo, ske->s2k.salt, 8,
2258                          S2K_DECODE_COUNT (ske->s2k.count),
2259                          /* The size of the desired key and its
2260                             buffer.  */
2261                          s2kdek.keylen, s2kdek.key);
2262   if (err)
2263     log_fatal ("gcry_kdf_derive failed: %s", gpg_strerror (err));
2264
2265
2266   if (si.s2k_is_session_key)
2267     {
2268       ske->seskeylen = 0;
2269       session_key = s2kdek;
2270     }
2271   else
2272     /* Encrypt the session key using the s2k specifier.  */
2273     {
2274       DEK *sesdekp = &sesdek;
2275
2276       /* Now encrypt the session key (or rather, the algorithm used to
2277          encrypt the SED plus the session key) using ENCKEY.  */
2278       ske->seskeylen = 1 + sesdek.keylen;
2279       encrypt_seskey (&s2kdek, &sesdekp, ske->seskey);
2280
2281       /* Save the session key for later.  */
2282       session_key = sesdek;
2283     }
2284
2285   pkt.pkttype = PKT_SYMKEY_ENC;
2286   pkt.pkt.symkey_enc = ske;
2287
2288   err = build_packet (out, &pkt);
2289   if (err)
2290     log_fatal ("Serializing sym-key encrypted packet: %s\n",
2291                gpg_strerror (err));
2292
2293   debug ("Wrote sym-key encrypted packet:\n");
2294   dump_component (&pkt);
2295
2296   xfree (si.session_key);
2297   xfree (si.password);
2298   xfree (ske);
2299
2300   return processed;
2301 }
2302 \f
2303 struct pk_esk_info
2304 {
2305   int session_key_set;
2306
2307   int new_session_key;
2308
2309   int sed_cipher;
2310   int session_key_len;
2311   char *session_key;
2312
2313   int throw_keyid;
2314
2315   char *keyid;
2316 };
2317
2318 static int
2319 pk_esk_session_key (const char *option, int argc, char *argv[], void *cookie)
2320 {
2321   struct pk_esk_info *pi = cookie;
2322   char *usage = "HEX-CHARACTERS|auto|none";
2323   char *p = argv[0];
2324   struct session_key sk;
2325
2326   if (argc == 0)
2327     log_fatal ("Usage: %s %s\n", option, usage);
2328
2329   if (pi->session_key_set)
2330     log_fatal ("%s given multiple times.", option);
2331   pi->session_key_set = 1;
2332
2333   if (strcasecmp (p, "new") == 0)
2334     {
2335       pi->new_session_key = 1;
2336       return 1;
2337     }
2338
2339   if (strcasecmp (p, "auto") == 0)
2340     return 1;
2341
2342   sk = parse_session_key (option, p, 0);
2343
2344   if (pi->session_key)
2345     log_fatal ("%s given multiple times.", option);
2346
2347   if (sk.algo)
2348     pi->sed_cipher = sk.algo;
2349
2350   pi->session_key_len = sk.keylen;
2351   pi->session_key = sk.key;
2352
2353   return 1;
2354 }
2355
2356 static int
2357 pk_esk_throw_keyid (const char *option, int argc, char *argv[], void *cookie)
2358 {
2359   struct pk_esk_info *pi = cookie;
2360
2361   (void) option;
2362   (void) argc;
2363   (void) argv;
2364
2365   pi->throw_keyid = 1;
2366
2367   return 0;
2368 }
2369
2370 static int
2371 pk_esk_keyid (const char *option, int argc, char *argv[], void *cookie)
2372 {
2373   struct pk_esk_info *pi = cookie;
2374   char *usage = "KEYID";
2375
2376   if (argc == 0)
2377     log_fatal ("Usage: %s %s\n", option, usage);
2378
2379   if (pi->keyid)
2380     log_fatal ("Multiple key ids given, but only one is allowed.");
2381
2382   pi->keyid = xstrdup (argv[0]);
2383
2384   return 1;
2385 }
2386
2387 static struct option pk_esk_options[] = {
2388   { "--session-key", pk_esk_session_key,
2389     "The session key to be encrypted by the S2K function as a hexadecimal "
2390     "string.  If this is not given or is \"auto\", then the current "
2391     "session key is used.  If there is no session key or this is \"new\", "
2392     "then a new session key is generated.  The session key may be "
2393     "prefaced with an integer and a colon to indicate the cipher to use "
2394     "for the SED packet (making --sed-cipher unnecessary and allowing the "
2395     "direct use of the result of \"" GPG_NAME " --show-session-key\")." },
2396   { "--throw-keyid", pk_esk_throw_keyid,
2397     "Throw the keyid." },
2398   { "", pk_esk_keyid, "The key id." },
2399   { NULL, NULL,
2400     "Example:\n\n"
2401     "  $ gpgcompose --pk-esk $KEYID --encrypted --literal --value foo \\\n"
2402     "  | " GPG_NAME " --list-packets"}
2403 };
2404
2405 static int
2406 pk_esk (const char *option, int argc, char *argv[], void *cookie)
2407 {
2408   iobuf_t out = cookie;
2409   gpg_error_t err;
2410   int processed;
2411   struct pk_esk_info pi;
2412   PKT_public_key pk;
2413
2414   memset (&pi, 0, sizeof (pi));
2415
2416   processed = process_options (option,
2417                                major_options,
2418                                pk_esk_options, &pi,
2419                                global_options, NULL,
2420                                argc, argv);
2421
2422   if (! pi.keyid)
2423     log_fatal ("%s: missing keyid.  Usage: %s KEYID", option, option);
2424
2425   memset (&pk, 0, sizeof (pk));
2426   pk.req_usage = PUBKEY_USAGE_ENC;
2427   err = get_pubkey_byname (NULL, NULL, &pk, pi.keyid, NULL, NULL, 1, 1);
2428   if (err)
2429     log_fatal ("%s: looking up key %s: %s\n",
2430                option, pi.keyid, gpg_strerror (err));
2431
2432   if (pi.sed_cipher)
2433     /* Have a session key.  */
2434     {
2435       session_key.algo = pi.sed_cipher;
2436       session_key.keylen = pi.session_key_len;
2437       log_assert (session_key.keylen <= sizeof (session_key.key));
2438       memcpy (session_key.key, pi.session_key, session_key.keylen);
2439     }
2440
2441   if (pi.new_session_key || ! session_key.algo)
2442     {
2443       if (! pi.new_session_key)
2444         /* Default to AES256.  */
2445         session_key.algo = CIPHER_ALGO_AES256;
2446       make_session_key (&session_key);
2447     }
2448
2449   err = write_pubkey_enc (&pk, pi.throw_keyid, &session_key, out);
2450   if (err)
2451     log_fatal ("%s: writing pk_esk packet for %s: %s\n",
2452                option, pi.keyid, gpg_strerror (err));
2453
2454   debug ("Wrote pk_esk packet for %s\n", pi.keyid);
2455
2456   xfree (pi.keyid);
2457   xfree (pi.session_key);
2458
2459   return processed;
2460 }
2461 \f
2462 struct encinfo
2463 {
2464   int saw_session_key;
2465 };
2466
2467 static int
2468 encrypted_session_key (const char *option, int argc, char *argv[], void *cookie)
2469 {
2470   struct encinfo *ei = cookie;
2471   char *usage = "HEX-CHARACTERS|auto";
2472   char *p = argv[0];
2473   struct session_key sk;
2474
2475   if (argc == 0)
2476     log_fatal ("Usage: %s %s\n", option, usage);
2477
2478   if (ei->saw_session_key)
2479     log_fatal ("%s given multiple times.", option);
2480   ei->saw_session_key = 1;
2481
2482   if (strcasecmp (p, "auto") == 0)
2483     return 1;
2484
2485   sk = parse_session_key (option, p, 1);
2486
2487   session_key.algo = sk.algo;
2488   log_assert (sk.keylen <= sizeof (session_key.key));
2489   memcpy (session_key.key, sk.key, sk.keylen);
2490   xfree (sk.key);
2491
2492   return 1;
2493 }
2494
2495 static struct option encrypted_options[] = {
2496   { "--session-key", encrypted_session_key,
2497     "The session key to be encrypted by the S2K function as a hexadecimal "
2498     "string.  If this is not given or is \"auto\", then the last session key "
2499     "is used.  If there was none, then an error is raised.  The session key "
2500     "must be prefaced with an integer and a colon to indicate the cipher "
2501     "to use (this is format used by \"" GPG_NAME " --show-session-key\")." },
2502   { NULL, NULL,
2503     "After creating the packet, this command clears the current "
2504     "session key.\n\n"
2505     "Example: nested encryption packets:\n\n"
2506     "  $ gpgcompose --sk-esk foo --encrypted-mdc \\\n"
2507     "  --sk-esk bar --encrypted-mdc \\\n"
2508     "  --literal --value 123 --encrypted-pop --encrypted-pop | " GPG_NAME" -d" }
2509 };
2510
2511 static int
2512 encrypted (const char *option, int argc, char *argv[], void *cookie)
2513 {
2514   iobuf_t out = cookie;
2515   int processed;
2516   struct encinfo ei;
2517   PKT_encrypted e;
2518   cipher_filter_context_t *cfx;
2519
2520   memset (&ei, 0, sizeof (ei));
2521
2522   processed = process_options (option,
2523                                major_options,
2524                                encrypted_options, &ei,
2525                                global_options, NULL,
2526                                argc, argv);
2527
2528   if (! session_key.algo)
2529     log_fatal ("%s: no session key configured.\n", option);
2530
2531   memset (&e, 0, sizeof (e));
2532   /* We only need to set E->LEN, E->EXTRALEN (if E->LEN is not
2533      0), and E->NEW_CTB.  */
2534   e.len = 0;
2535   e.new_ctb = 1;
2536
2537   /* Register the cipher filter. */
2538
2539   cfx = xmalloc_clear (sizeof (*cfx));
2540
2541   /* Copy the session key.  */
2542   cfx->dek = xmalloc (sizeof (*cfx->dek));
2543   *cfx->dek = session_key;
2544
2545   if (do_debug)
2546     {
2547       char *buf;
2548
2549       buf = xmalloc (2 * session_key.keylen + 1);
2550       debug ("session key: algo: %d; keylen: %d; key: %s\n",
2551              session_key.algo, session_key.keylen,
2552              bin2hex (session_key.key, session_key.keylen, buf));
2553       xfree (buf);
2554     }
2555
2556   if (strcmp (option, "--encrypted-mdc") == 0)
2557     cfx->dek->use_mdc = 1;
2558   else if (strcmp (option, "--encrypted") == 0)
2559     cfx->dek->use_mdc = 0;
2560   else
2561     log_fatal ("%s: option not handled by this function!\n", option);
2562
2563   cfx->datalen = 0;
2564
2565   filter_push (out, cipher_filter, cfx, PKT_ENCRYPTED, cfx->datalen == 0);
2566
2567   debug ("Wrote encrypted packet:\n");
2568
2569   /* Clear the current session key.  */
2570   memset (&session_key, 0, sizeof (session_key));
2571
2572   return processed;
2573 }
2574 \f
2575 static int
2576 encrypted_pop (const char *option, int argc, char *argv[], void *cookie)
2577 {
2578   iobuf_t out = cookie;
2579
2580   (void) argc;
2581   (void) argv;
2582
2583   if (strcmp (option, "--encrypted-pop") == 0)
2584     filter_pop (out, PKT_ENCRYPTED);
2585   else if (strcmp (option, "--encrypted-mdc-pop") == 0)
2586     filter_pop (out, PKT_ENCRYPTED_MDC);
2587   else
2588     log_fatal ("%s: option not handled by this function!\n", option);
2589
2590   debug ("Popped encryption container.\n");
2591
2592   return 0;
2593 }
2594 \f
2595 struct data
2596 {
2597   int file;
2598   union
2599   {
2600     char *data;
2601     char *filename;
2602   };
2603   struct data *next;
2604 };
2605
2606 /* This must be the first member of the struct to be able to use
2607    add_value!  */
2608 struct datahead
2609 {
2610   struct data *head;
2611   struct data **last_next;
2612 };
2613
2614 static int
2615 add_value (const char *option, int argc, char *argv[], void *cookie)
2616 {
2617   struct datahead *dh = cookie;
2618   struct data *d = xmalloc_clear (sizeof (struct data));
2619
2620   d->file = strcmp ("--file", option) == 0;
2621   if (! d->file)
2622     log_assert (strcmp ("--value", option) == 0);
2623
2624   if (argc == 0)
2625     {
2626       if (d->file)
2627         log_fatal ("Usage: %s FILENAME\n", option);
2628       else
2629         log_fatal ("Usage: %s STRING\n", option);
2630     }
2631
2632   if (! dh->last_next)
2633     /* First time through.  Initialize DH->LAST_NEXT.  */
2634     {
2635       log_assert (! dh->head);
2636       dh->last_next = &dh->head;
2637     }
2638
2639   if (d->file)
2640     d->filename = argv[0];
2641   else
2642     d->data = argv[0];
2643
2644   /* Append it.  */
2645   *dh->last_next = d;
2646   dh->last_next = &d->next;
2647
2648   return 1;
2649 }
2650 \f
2651 struct litinfo
2652 {
2653   /* This must be the first element for add_value to work!  */
2654   struct datahead data;
2655
2656   int timestamp_set;
2657   u32 timestamp;
2658   char mode;
2659   int partial_body_length_encoding;
2660   char *name;
2661 };
2662
2663 static int
2664 literal_timestamp (const char *option, int argc, char *argv[], void *cookie)
2665 {
2666   struct litinfo *li = cookie;
2667
2668   char *tail = NULL;
2669
2670   if (argc == 0)
2671     log_fatal ("Usage: %s TIMESTAMP\n", option);
2672
2673   errno = 0;
2674   li->timestamp = parse_timestamp (argv[0], &tail);
2675   if (errno || (tail && *tail))
2676     log_fatal ("Invalid value passed to %s (%s)\n", option, argv[0]);
2677   li->timestamp_set = 1;
2678
2679   return 1;
2680 }
2681
2682 static int
2683 literal_mode (const char *option, int argc, char *argv[], void *cookie)
2684 {
2685   struct litinfo *li = cookie;
2686
2687   if (argc == 0
2688       || ! (strcmp (argv[0], "b") == 0
2689             || strcmp (argv[0], "t") == 0
2690             || strcmp (argv[0], "u") == 0))
2691     log_fatal ("Usage: %s [btu]\n", option);
2692
2693   li->mode = argv[0][0];
2694
2695   return 1;
2696 }
2697
2698 static int
2699 literal_partial_body_length (const char *option, int argc, char *argv[],
2700                              void *cookie)
2701 {
2702   struct litinfo *li = cookie;
2703   char *tail;
2704   int v;
2705   int range[2] = {0, 1};
2706
2707   if (argc <= 1)
2708     log_fatal ("Usage: %s [0|1]\n", option);
2709
2710   errno = 0;
2711   v = strtol (argv[0], &tail, 0);
2712   if (errno || (tail && *tail) || !(range[0] <= v && v <= range[1]))
2713     log_fatal ("Invalid value passed to %s (%s).  Expected %d-%d\n",
2714                option, argv[0], range[0], range[1]);
2715
2716   li->partial_body_length_encoding = v;
2717
2718   return 1;
2719 }
2720
2721 static int
2722 literal_name (const char *option, int argc, char *argv[], void *cookie)
2723 {
2724   struct litinfo *li = cookie;
2725
2726   if (argc <= 1)
2727     log_fatal ("Usage: %s NAME\n", option);
2728
2729   if (strlen (argv[0]) > 255)
2730     log_fatal ("%s: name is too long (%zd > 255 characters).\n",
2731                option, strlen (argv[0]));
2732
2733   li->name = argv[0];
2734
2735   return 1;
2736 }
2737
2738 static struct option literal_options[] = {
2739   { "--value", add_value,
2740     "A string to store in the literal packet." },
2741   { "--file", add_value,
2742     "A file to copy into the literal packet." },
2743   { "--timestamp", literal_timestamp,
2744     "The literal packet's time stamp.  This defaults to the current time." },
2745   { "--mode", literal_mode,
2746     "The content's mode (normally 'b' (default), 't' or 'u')." },
2747   { "--partial-body-length", literal_partial_body_length,
2748     "Force partial body length encoding." },
2749   { "--name", literal_name,
2750     "The literal's name." },
2751   { NULL, NULL,
2752     "Example:\n\n"
2753     "  $ gpgcompose --literal --value foobar | " GPG_NAME " -d"}
2754 };
2755
2756 static int
2757 literal (const char *option, int argc, char *argv[], void *cookie)
2758 {
2759   iobuf_t out = cookie;
2760   gpg_error_t err;
2761   int processed;
2762   struct litinfo li;
2763   PKT_plaintext *pt;
2764   PACKET pkt;
2765   struct data *data;
2766
2767   memset (&li, 0, sizeof (li));
2768
2769   processed = process_options (option,
2770                                major_options,
2771                                literal_options, &li,
2772                                global_options, NULL,
2773                                argc, argv);
2774
2775   if (! li.data.head)
2776     log_fatal ("%s: no data provided (use --value or --file)", option);
2777
2778   pt = xmalloc_clear (sizeof (*pt) + (li.name ? strlen (li.name) : 0));
2779   pt->new_ctb = 1;
2780
2781   if (li.timestamp_set)
2782     pt->timestamp = li.timestamp;
2783   else
2784     /* Default to the current time.  */
2785     pt->timestamp = make_timestamp ();
2786
2787   pt->mode = li.mode;
2788   if (! pt->mode)
2789     /* Default to binary.  */
2790     pt->mode = 'b';
2791
2792   if (li.name)
2793     {
2794       strcpy (pt->name, li.name);
2795       pt->namelen = strlen (pt->name);
2796     }
2797
2798   pkt.pkttype = PKT_PLAINTEXT;
2799   pkt.pkt.plaintext = pt;
2800
2801   if (! li.partial_body_length_encoding)
2802     /* Compute the amount of data.  */
2803     {
2804       pt->len = 0;
2805       for (data = li.data.head; data; data = data->next)
2806         {
2807           if (data->file)
2808             {
2809               iobuf_t in;
2810               int overflow;
2811               off_t off;
2812
2813               in = iobuf_open (data->filename);
2814               if (! in)
2815                 /* An error opening the file.  We do error handling
2816                    below so just break here.  */
2817                 {
2818                   pt->len = 0;
2819                   break;
2820                 }
2821
2822               off = iobuf_get_filelength (in, &overflow);
2823               iobuf_close (in);
2824
2825               if (overflow || off == 0)
2826                 /* Length is unknown or there was an error
2827                    (unfortunately, iobuf_get_filelength doesn't
2828                    distinguish between 0 length files and an error!).
2829                    Fall back to partial body mode.  */
2830                 {
2831                   pt->len = 0;
2832                   break;
2833                 }
2834
2835               pt->len += off;
2836             }
2837           else
2838             pt->len += strlen (data->data);
2839         }
2840     }
2841
2842   err = build_packet (out, &pkt);
2843   if (err)
2844     log_fatal ("Serializing literal packet: %s\n", gpg_strerror (err));
2845
2846   /* Write out the data.  */
2847   for (data = li.data.head; data; data = data->next)
2848     {
2849       if (data->file)
2850         {
2851           iobuf_t in;
2852           errno = 0;
2853           in = iobuf_open (data->filename);
2854           if (! in)
2855             log_fatal ("Opening '%s': %s\n",
2856                        data->filename,
2857                        errno ? strerror (errno): "unknown error");
2858
2859           iobuf_copy (out, in);
2860           if (iobuf_error (in))
2861             log_fatal ("Reading from %s: %s\n",
2862                        data->filename,
2863                        gpg_strerror (iobuf_error (in)));
2864           if (iobuf_error (out))
2865             log_fatal ("Writing literal data from %s: %s\n",
2866                        data->filename,
2867                        gpg_strerror (iobuf_error (out)));
2868
2869           iobuf_close (in);
2870         }
2871       else
2872         {
2873           err = iobuf_write (out, data->data, strlen (data->data));
2874           if (err)
2875             log_fatal ("Writing literal data: %s\n", gpg_strerror (err));
2876         }
2877     }
2878
2879   if (! pt->len)
2880     {
2881       /* Disable partial body length mode.  */
2882       log_assert (pt->new_ctb == 1);
2883       iobuf_set_partial_body_length_mode (out, 0);
2884     }
2885
2886   debug ("Wrote literal packet:\n");
2887   dump_component (&pkt);
2888
2889   while (li.data.head)
2890     {
2891       data = li.data.head->next;
2892       xfree (li.data.head);
2893       li.data.head = data;
2894     }
2895   xfree (pt);
2896
2897   return processed;
2898 }
2899 \f
2900 static int
2901 copy_file (const char *option, int argc, char *argv[], void *cookie)
2902 {
2903   char **filep = cookie;
2904
2905   if (argc == 0)
2906     log_fatal ("Usage: %s FILENAME\n", option);
2907
2908   *filep = argv[0];
2909
2910   return 1;
2911 }
2912
2913 static struct option copy_options[] = {
2914   { "", copy_file, "Copy the specified file to stdout." },
2915   { NULL, NULL,
2916     "Example:\n\n"
2917     "  $ gpgcompose --copy /etc/hostname\n\n"
2918     "This is particularly useful when combined with gpgsplit." }
2919 };
2920
2921 static int
2922 copy (const char *option, int argc, char *argv[], void *cookie)
2923 {
2924   iobuf_t out = cookie;
2925   char *file = NULL;
2926   iobuf_t in;
2927
2928   int processed;
2929
2930   processed = process_options (option,
2931                                major_options,
2932                                copy_options, &file,
2933                                global_options, NULL,
2934                                argc, argv);
2935   if (! file)
2936     log_fatal ("Usage: %s FILE\n", option);
2937
2938   errno = 0;
2939   in = iobuf_open (file);
2940   if (! in)
2941     log_fatal ("Error opening %s: %s.\n",
2942                file, errno ? strerror (errno): "unknown error");
2943
2944   iobuf_copy (out, in);
2945   if (iobuf_error (out))
2946     log_fatal ("Copying data to destination: %s\n",
2947                gpg_strerror (iobuf_error (out)));
2948   if (iobuf_error (in))
2949     log_fatal ("Reading data from %s: %s\n",
2950                argv[0], gpg_strerror (iobuf_error (in)));
2951
2952   iobuf_close (in);
2953
2954   return processed;
2955 }
2956 \f
2957 int
2958 main (int argc, char *argv[])
2959 {
2960   const char *filename = "-";
2961   iobuf_t out;
2962   int preprocessed = 1;
2963   int processed;
2964   ctrl_t ctrl;
2965
2966   opt.ignore_time_conflict = 1;
2967   /* Allow notations in the IETF space, for instance.  */
2968   opt.expert = 1;
2969
2970   ctrl = xcalloc (1, sizeof *ctrl);
2971
2972   keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
2973                       KEYDB_RESOURCE_FLAG_DEFAULT);
2974
2975   if (argc == 1)
2976     /* Nothing to do.  */
2977     return 0;
2978
2979   if (strcmp (argv[1], "--output") == 0
2980       || strcmp (argv[1], "-o") == 0)
2981     {
2982       filename = argv[2];
2983       log_info ("Writing to %s\n", filename);
2984       preprocessed += 2;
2985     }
2986
2987   out = iobuf_create (filename, 0);
2988   if (! out)
2989     log_fatal ("Failed to open stdout for writing\n");
2990
2991   processed = process_options (NULL, NULL,
2992                                major_options, out,
2993                                global_options, NULL,
2994                                argc - preprocessed, &argv[preprocessed]);
2995   if (processed != argc - preprocessed)
2996     log_fatal ("Didn't process %d options.\n", argc - preprocessed - processed);
2997
2998   iobuf_close (out);
2999
3000   return 0;
3001 }
3002 \f
3003 /* Stubs duplicated from gpg.c.  */
3004
3005 int g10_errors_seen = 0;
3006
3007 /* Note: This function is used by signal handlers!. */
3008 static void
3009 emergency_cleanup (void)
3010 {
3011   gcry_control (GCRYCTL_TERM_SECMEM );
3012 }
3013
3014 void
3015 g10_exit( int rc )
3016 {
3017   gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
3018
3019   emergency_cleanup ();
3020
3021   rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
3022   exit (rc);
3023 }
3024
3025 void
3026 keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr,
3027               strlist_t commands, int quiet, int seckey_check)
3028 {
3029   (void) ctrl;
3030   (void) username;
3031   (void) locusr;
3032   (void) commands;
3033   (void) quiet;
3034   (void) seckey_check;
3035 }
3036
3037 void
3038 show_basic_key_info (KBNODE keyblock)
3039 {
3040   (void) keyblock;
3041 }