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