0feda90b1e749a087540a49255499c38a2d988aa
[platform/upstream/gpg2.git] / sm / gpgsm.c
1 /* gpgsm.c - GnuPG for S/MIME
2  * Copyright (C) 2001-2008, 2010  Free Software Foundation, Inc.
3  * Copyright (C) 2001-2008, 2010  Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 /*#include <mcheck.h>*/
30
31 #include "gpgsm.h"
32 #include <gcrypt.h>
33 #include <assuan.h> /* malloc hooks */
34
35 #include "passphrase.h"
36 #include "../common/shareddefs.h"
37 #include "../kbx/keybox.h" /* malloc hooks */
38 #include "../common/i18n.h"
39 #include "keydb.h"
40 #include "../common/sysutils.h"
41 #include "../common/gc-opt-flags.h"
42 #include "../common/asshelp.h"
43 #include "../common/init.h"
44 #include "../common/compliance.h"
45
46
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 enum cmd_and_opt_values {
52   aNull = 0,
53   oArmor        = 'a',
54   aDetachedSign = 'b',
55   aSym          = 'c',
56   aDecrypt      = 'd',
57   aEncr         = 'e',
58   aListKeys     = 'k',
59   aListSecretKeys = 'K',
60   oDryRun       = 'n',
61   oOutput       = 'o',
62   oQuiet        = 'q',
63   oRecipient    = 'r',
64   aSign         = 's',
65   oUser         = 'u',
66   oVerbose      = 'v',
67   oBatch        = 500,
68   aClearsign,
69   aKeygen,
70   aSignEncr,
71   aDeleteKey,
72   aImport,
73   aVerify,
74   aListExternalKeys,
75   aListChain,
76   aSendKeys,
77   aRecvKeys,
78   aExport,
79   aExportSecretKeyP12,
80   aExportSecretKeyP8,
81   aExportSecretKeyRaw,
82   aServer,
83   aLearnCard,
84   aCallDirmngr,
85   aCallProtectTool,
86   aPasswd,
87   aGPGConfList,
88   aGPGConfTest,
89   aDumpKeys,
90   aDumpChain,
91   aDumpSecretKeys,
92   aDumpExternalKeys,
93   aKeydbClearSomeCertFlags,
94   aFingerprint,
95
96   oOptions,
97   oDebug,
98   oDebugLevel,
99   oDebugAll,
100   oDebugNone,
101   oDebugWait,
102   oDebugAllowCoreDump,
103   oDebugNoChainValidation,
104   oDebugIgnoreExpiration,
105   oLogFile,
106   oNoLogFile,
107   oAuditLog,
108   oHtmlAuditLog,
109
110   oEnableSpecialFilenames,
111
112   oAgentProgram,
113   oDisplay,
114   oTTYname,
115   oTTYtype,
116   oLCctype,
117   oLCmessages,
118   oXauthority,
119
120   oPreferSystemDirmngr,
121   oDirmngrProgram,
122   oDisableDirmngr,
123   oProtectToolProgram,
124   oFakedSystemTime,
125
126   oPassphraseFD,
127   oPinentryMode,
128
129   oAssumeArmor,
130   oAssumeBase64,
131   oAssumeBinary,
132
133   oBase64,
134   oNoArmor,
135   oP12Charset,
136
137   oCompliance,
138
139   oDisableCRLChecks,
140   oEnableCRLChecks,
141   oDisableTrustedCertCRLCheck,
142   oEnableTrustedCertCRLCheck,
143   oForceCRLRefresh,
144
145   oDisableOCSP,
146   oEnableOCSP,
147
148   oIncludeCerts,
149   oPolicyFile,
150   oDisablePolicyChecks,
151   oEnablePolicyChecks,
152   oAutoIssuerKeyRetrieve,
153
154   oWithFingerprint,
155   oWithMD5Fingerprint,
156   oWithKeygrip,
157   oWithSecret,
158   oAnswerYes,
159   oAnswerNo,
160   oKeyring,
161   oDefaultKey,
162   oDefRecipient,
163   oDefRecipientSelf,
164   oNoDefRecipient,
165   oStatusFD,
166   oCipherAlgo,
167   oDigestAlgo,
168   oExtraDigestAlgo,
169   oNoVerbose,
170   oNoSecmemWarn,
171   oNoDefKeyring,
172   oNoGreeting,
173   oNoTTY,
174   oNoOptions,
175   oNoBatch,
176   oHomedir,
177   oWithColons,
178   oWithKeyData,
179   oWithValidation,
180   oWithEphemeralKeys,
181   oSkipVerify,
182   oValidationModel,
183   oKeyServer,
184   oEncryptTo,
185   oNoEncryptTo,
186   oLoggerFD,
187   oDisableCipherAlgo,
188   oDisablePubkeyAlgo,
189   oIgnoreTimeConflict,
190   oNoRandomSeedFile,
191   oNoCommonCertsImport,
192   oIgnoreCertExtension,
193   oNoAutostart
194  };
195
196
197 static ARGPARSE_OPTS opts[] = {
198
199   ARGPARSE_group (300, N_("@Commands:\n ")),
200
201   ARGPARSE_c (aSign, "sign", N_("make a signature")),
202 /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
203   ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
204   ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
205 /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
206   ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
207   ARGPARSE_c (aVerify, "verify",  N_("verify a signature")),
208   ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
209   ARGPARSE_c (aListExternalKeys, "list-external-keys",
210               N_("list external keys")),
211   ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
212   ARGPARSE_c (aListChain,   "list-chain",  N_("list certificate chain")),
213   ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
214   ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")),
215   ARGPARSE_c (aKeygen, "gen-key", "@"),
216   ARGPARSE_c (aDeleteKey, "delete-keys",
217               N_("remove keys from the public keyring")),
218 /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
219 /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
220   ARGPARSE_c (aImport, "import", N_("import certificates")),
221   ARGPARSE_c (aExport, "export", N_("export certificates")),
222
223   /* We use -raw and not -p1 for pkcs#1 secret key export so that it
224      won't accidentally be used in case -p12 was intended.  */
225   ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
226   ARGPARSE_c (aExportSecretKeyP8,  "export-secret-key-p8", "@"),
227   ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
228
229   ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
230   ARGPARSE_c (aServer, "server", N_("run in server mode")),
231   ARGPARSE_c (aCallDirmngr, "call-dirmngr",
232               N_("pass a command to the dirmngr")),
233   ARGPARSE_c (aCallProtectTool, "call-protect-tool",
234               N_("invoke gpg-protect-tool")),
235   ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
236   ARGPARSE_c (aPasswd, "passwd", "@"),
237   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
238   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
239
240   ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
241   ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
242   ARGPARSE_c (aDumpChain, "dump-chain", "@"),
243   ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
244   ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
245   ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
246
247   ARGPARSE_group (301, N_("@\nOptions:\n ")),
248
249   ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
250   ARGPARSE_s_n (oArmor, "armour", "@"),
251   ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
252
253   ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
254
255   ARGPARSE_s_i (oPassphraseFD,    "passphrase-fd", "@"),
256   ARGPARSE_s_s (oPinentryMode,    "pinentry-mode", "@"),
257
258   ARGPARSE_s_n (oAssumeArmor, "assume-armor",
259                 N_("assume input is in PEM format")),
260   ARGPARSE_s_n (oAssumeBase64, "assume-base64",
261                 N_("assume input is in base-64 format")),
262   ARGPARSE_s_n (oAssumeBinary, "assume-binary",
263                 N_("assume input is in binary format")),
264
265   ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
266
267   ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
268
269   ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
270                 N_("never consult a CRL")),
271   ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
272   ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
273                 "disable-trusted-cert-crl-check", "@"),
274   ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
275                 "enable-trusted-cert-crl-check", "@"),
276
277   ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
278
279   ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
280   ARGPARSE_s_n (oEnableOCSP,  "enable-ocsp", N_("check validity using OCSP")),
281
282   ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
283
284   ARGPARSE_s_i (oIncludeCerts, "include-certs",
285                 N_("|N|number of certificates to include") ),
286
287   ARGPARSE_s_s (oPolicyFile, "policy-file",
288                 N_("|FILE|take policy information from FILE")),
289
290   ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
291                 N_("do not check certificate policies")),
292   ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
293
294   ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
295                 N_("fetch missing issuer certificates")),
296
297   ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
298   ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
299
300   ARGPARSE_s_s (oUser, "local-user",
301                 N_("|USER-ID|use USER-ID to sign or decrypt")),
302
303   ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
304   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
305   ARGPARSE_s_n (oQuiet, "quiet",  N_("be somewhat more quiet")),
306   ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
307   ARGPARSE_s_s (oLogFile, "log-file",
308                 N_("|FILE|write a server mode log to FILE")),
309   ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
310   ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
311
312   ARGPARSE_s_s (oAuditLog, "audit-log",
313                 N_("|FILE|write an audit log to FILE")),
314   ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
315   ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
316   ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
317   ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
318   ARGPARSE_s_n (oAnswerNo,  "no",  N_("assume no on most questions")),
319
320   ARGPARSE_s_s (oKeyring, "keyring",
321                 N_("|FILE|add keyring to the list of keyrings")),
322
323   ARGPARSE_s_s (oDefaultKey, "default-key",
324                 N_("|USER-ID|use USER-ID as default secret key")),
325
326   /* Not yet used: */
327   /*   ARGPARSE_s_s (oDefRecipient, "default-recipient", */
328   /*                  N_("|NAME|use NAME as default recipient")), */
329   /*   ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
330   /*                  N_("use the default key as default recipient")), */
331   /*   ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
332
333   ARGPARSE_s_s (oKeyServer, "keyserver",
334                 N_("|SPEC|use this keyserver to lookup keys")),
335   ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
336
337   ARGPARSE_s_s (oDebug, "debug", "@"),
338   ARGPARSE_s_s (oDebugLevel, "debug-level",
339                 N_("|LEVEL|set the debugging level to LEVEL")),
340   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
341   ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
342   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
343   ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
344   ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
345   ARGPARSE_s_n (oDebugIgnoreExpiration,  "debug-ignore-expiration", "@"),
346
347   ARGPARSE_s_i (oStatusFD, "status-fd",
348                 N_("|FD|write status info to this FD")),
349
350   ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
351                 N_("|NAME|use cipher algorithm NAME")),
352   ARGPARSE_s_s (oDigestAlgo, "digest-algo",
353                 N_("|NAME|use message digest algorithm NAME")),
354   ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
355
356
357   ARGPARSE_group (302, N_(
358   "@\n(See the man page for a complete listing of all commands and options)\n"
359   )),
360
361
362   /* Hidden options. */
363   ARGPARSE_s_s (oCompliance, "compliance",   "@"),
364   ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
365   ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
366   ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
367   ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
368   ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
369   ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
370   ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
371   ARGPARSE_s_n (oNoOptions, "no-options", "@"),
372   ARGPARSE_s_s (oHomedir, "homedir", "@"),
373   ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
374   ARGPARSE_s_s (oDisplay,    "display", "@"),
375   ARGPARSE_s_s (oTTYname,    "ttyname", "@"),
376   ARGPARSE_s_s (oTTYtype,    "ttytype", "@"),
377   ARGPARSE_s_s (oLCctype,    "lc-ctype", "@"),
378   ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
379   ARGPARSE_s_s (oXauthority, "xauthority", "@"),
380   ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
381   ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
382   ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
383   ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
384   ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
385   ARGPARSE_s_n (oWithColons, "with-colons", "@"),
386   ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
387   ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
388   ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
389   ARGPARSE_s_n (oWithEphemeralKeys,  "with-ephemeral-keys", "@"),
390   ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
391   ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
392   ARGPARSE_s_n (oWithKeygrip,     "with-keygrip", "@"),
393   ARGPARSE_s_n (oWithSecret,      "with-secret", "@"),
394   ARGPARSE_s_s (oDisableCipherAlgo,  "disable-cipher-algo", "@"),
395   ARGPARSE_s_s (oDisablePubkeyAlgo,  "disable-pubkey-algo", "@"),
396   ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
397   ARGPARSE_s_n (oNoRandomSeedFile,  "no-random-seed-file", "@"),
398   ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
399   ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
400   ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
401
402   /* Command aliases.  */
403   ARGPARSE_c (aListKeys, "list-key", "@"),
404   ARGPARSE_c (aListChain, "list-signatures", "@"),
405   ARGPARSE_c (aListChain, "list-sigs", "@"),
406   ARGPARSE_c (aListChain, "check-signatures", "@"),
407   ARGPARSE_c (aListChain, "check-sigs", "@"),
408   ARGPARSE_c (aDeleteKey, "delete-key", "@"),
409
410   ARGPARSE_end ()
411 };
412
413
414 /* The list of supported debug flags.  */
415 static struct debug_flags_s debug_flags [] =
416   {
417     { DBG_X509_VALUE   , "x509"    },
418     { DBG_MPI_VALUE    , "mpi"     },
419     { DBG_CRYPTO_VALUE , "crypto"  },
420     { DBG_MEMORY_VALUE , "memory"  },
421     { DBG_CACHE_VALUE  , "cache"   },
422     { DBG_MEMSTAT_VALUE, "memstat" },
423     { DBG_HASHING_VALUE, "hashing" },
424     { DBG_IPC_VALUE    , "ipc"     },
425     { 0, NULL }
426   };
427
428
429 /* Global variable to keep an error count. */
430 int gpgsm_errors_seen = 0;
431
432 /* It is possible that we are currentlu running under setuid permissions */
433 static int maybe_setuid = 1;
434
435 /* Helper to implement --debug-level and --debug*/
436 static const char *debug_level;
437 static unsigned int debug_value;
438
439 /* Default value for include-certs.  We need an extra macro for
440    gpgconf-list because the variable will be changed by the command
441    line option.
442
443    It is often cumbersome to locate intermediate certificates, thus by
444    default we include all certificates in the chain.  However we leave
445    out the root certificate because that would make it too easy for
446    the recipient to import that root certificate.  A root certificate
447    should be installed only after due checks and thus it won't help to
448    send it along with each message.  */
449 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
450 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
451
452 /* Whether the chain mode shall be used for validation.  */
453 static int default_validation_model;
454
455 /* The default cipher algo.  */
456 #define DEFAULT_CIPHER_ALGO "AES"
457
458
459 static char *build_list (const char *text,
460                          const char *(*mapf)(int), int (*chkf)(int));
461 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
462                      enum cmd_and_opt_values new_cmd );
463
464 static void emergency_cleanup (void);
465 static int open_read (const char *filename);
466 static estream_t open_es_fread (const char *filename, const char *mode);
467 static estream_t open_es_fwrite (const char *filename);
468 static void run_protect_tool (int argc, char **argv);
469
470 static int
471 our_pk_test_algo (int algo)
472 {
473   switch (algo)
474     {
475     case GCRY_PK_RSA:
476     case GCRY_PK_ECDSA:
477       return gcry_pk_test_algo (algo);
478     default:
479       return 1;
480     }
481 }
482
483 static int
484 our_cipher_test_algo (int algo)
485 {
486   switch (algo)
487     {
488     case GCRY_CIPHER_3DES:
489     case GCRY_CIPHER_AES128:
490     case GCRY_CIPHER_AES192:
491     case GCRY_CIPHER_AES256:
492     case GCRY_CIPHER_SERPENT128:
493     case GCRY_CIPHER_SERPENT192:
494     case GCRY_CIPHER_SERPENT256:
495     case GCRY_CIPHER_SEED:
496     case GCRY_CIPHER_CAMELLIA128:
497     case GCRY_CIPHER_CAMELLIA192:
498     case GCRY_CIPHER_CAMELLIA256:
499       return gcry_cipher_test_algo (algo);
500     default:
501       return 1;
502     }
503 }
504
505
506 static int
507 our_md_test_algo (int algo)
508 {
509   switch (algo)
510     {
511     case GCRY_MD_MD5:
512     case GCRY_MD_SHA1:
513     case GCRY_MD_RMD160:
514     case GCRY_MD_SHA224:
515     case GCRY_MD_SHA256:
516     case GCRY_MD_SHA384:
517     case GCRY_MD_SHA512:
518     case GCRY_MD_WHIRLPOOL:
519       return gcry_md_test_algo (algo);
520     default:
521       return 1;
522     }
523 }
524
525
526 static char *
527 make_libversion (const char *libname, const char *(*getfnc)(const char*))
528 {
529   const char *s;
530   char *result;
531
532   if (maybe_setuid)
533     {
534       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
535       maybe_setuid = 0;
536     }
537   s = getfnc (NULL);
538   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
539   strcpy (stpcpy (stpcpy (result, libname), " "), s);
540   return result;
541 }
542
543
544 static const char *
545 my_strusage( int level )
546 {
547   static char *digests, *pubkeys, *ciphers;
548   static char *ver_gcry, *ver_ksba;
549   const char *p;
550
551   switch (level)
552     {
553     case 11: p = "@GPGSM@ (@GNUPG@)";
554       break;
555     case 13: p = VERSION; break;
556     case 17: p = PRINTABLE_OS_NAME; break;
557     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
558
559     case 1:
560     case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
561       break;
562     case 41:
563       p = _("Syntax: @GPGSM@ [options] [files]\n"
564             "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
565             "Default operation depends on the input data\n");
566       break;
567
568     case 20:
569       if (!ver_gcry)
570         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
571       p = ver_gcry;
572       break;
573     case 21:
574       if (!ver_ksba)
575         ver_ksba = make_libversion ("libksba", ksba_check_version);
576       p = ver_ksba;
577       break;
578
579     case 31: p = "\nHome: "; break;
580     case 32: p = gnupg_homedir (); break;
581     case 33: p = _("\nSupported algorithms:\n"); break;
582     case 34:
583       if (!ciphers)
584         ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
585                               our_cipher_test_algo );
586       p = ciphers;
587       break;
588     case 35:
589       if (!pubkeys)
590         pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
591                               our_pk_test_algo );
592       p = pubkeys;
593       break;
594     case 36:
595       if (!digests)
596         digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
597       p = digests;
598       break;
599
600     default: p = NULL; break;
601     }
602   return p;
603 }
604
605
606 static char *
607 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
608 {
609   int i;
610   size_t n=strlen(text)+2;
611   char *list, *p;
612
613   if (maybe_setuid) {
614     gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
615   }
616
617   for (i=1; i < 400; i++ )
618     if (!chkf(i))
619       n += strlen(mapf(i)) + 2;
620   list = xmalloc (21 + n);
621   *list = 0;
622   for (p=NULL, i=1; i < 400; i++)
623     {
624       if (!chkf(i))
625         {
626           if( !p )
627             p = stpcpy (list, text );
628           else
629             p = stpcpy (p, ", ");
630           p = stpcpy (p, mapf(i) );
631         }
632     }
633   if (p)
634     strcpy (p, "\n" );
635   return list;
636 }
637
638
639 /* Set the file pointer into binary mode if required.  */
640 static void
641 set_binary (FILE *fp)
642 {
643 #ifdef HAVE_DOSISH_SYSTEM
644   setmode (fileno (fp), O_BINARY);
645 #else
646   (void)fp;
647 #endif
648 }
649
650
651
652 static void
653 wrong_args (const char *text)
654 {
655   fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
656   gpgsm_exit (2);
657 }
658
659
660 static void
661 set_opt_session_env (const char *name, const char *value)
662 {
663   gpg_error_t err;
664
665   err = session_env_setenv (opt.session_env, name, value);
666   if (err)
667     log_fatal ("error setting session environment: %s\n",
668                gpg_strerror (err));
669 }
670
671
672 /* Setup the debugging.  With a DEBUG_LEVEL of NULL only the active
673    debug flags are propagated to the subsystems.  With DEBUG_LEVEL
674    set, a specific set of debug flags is set; and individual debugging
675    flags will be added on top.  */
676 static void
677 set_debug (void)
678 {
679   int numok = (debug_level && digitp (debug_level));
680   int numlvl = numok? atoi (debug_level) : 0;
681
682   if (!debug_level)
683     ;
684   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
685     opt.debug = 0;
686   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
687     opt.debug = DBG_IPC_VALUE;
688   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
689     opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
690   else if (!strcmp (debug_level, "expert")  || (numok && numlvl <= 8))
691     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
692                  |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
693   else if (!strcmp (debug_level, "guru") || numok)
694     {
695       opt.debug = ~0;
696       /* Unless the "guru" string has been used we don't want to allow
697          hashing debugging.  The rationale is that people tend to
698          select the highest debug value and would then clutter their
699          disk with debug files which may reveal confidential data.  */
700       if (numok)
701         opt.debug &= ~(DBG_HASHING_VALUE);
702     }
703   else
704     {
705       log_error (_("invalid debug-level '%s' given\n"), debug_level);
706       gpgsm_exit (2);
707     }
708
709   opt.debug |= debug_value;
710
711   if (opt.debug && !opt.verbose)
712     opt.verbose = 1;
713   if (opt.debug)
714     opt.quiet = 0;
715
716   if (opt.debug & DBG_MPI_VALUE)
717     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
718   if (opt.debug & DBG_CRYPTO_VALUE )
719     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
720   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
721
722   if (opt.debug)
723     parse_debug_flag (NULL, &opt.debug, debug_flags);
724 }
725
726
727
728 static void
729 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
730 {
731   enum cmd_and_opt_values cmd = *ret_cmd;
732
733   if (!cmd || cmd == new_cmd)
734     cmd = new_cmd;
735   else if ( cmd == aSign && new_cmd == aEncr )
736     cmd = aSignEncr;
737   else if ( cmd == aEncr && new_cmd == aSign )
738     cmd = aSignEncr;
739   else if ( (cmd == aSign && new_cmd == aClearsign)
740             || (cmd == aClearsign && new_cmd == aSign) )
741     cmd = aClearsign;
742   else
743     {
744       log_error(_("conflicting commands\n"));
745       gpgsm_exit(2);
746     }
747
748   *ret_cmd = cmd;
749 }
750
751
752 /* Helper to add recipients to a list. */
753 static void
754 do_add_recipient (ctrl_t ctrl, const char *name,
755                   certlist_t *recplist, int is_encrypt_to, int recp_required)
756 {
757   int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
758   if (rc)
759     {
760       if (recp_required)
761         {
762           log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
763           gpgsm_status2 (ctrl, STATUS_INV_RECP,
764                          get_inv_recpsgnr_code (rc), name, NULL);
765         }
766       else
767         log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
768                   name, gpg_strerror (rc));
769     }
770 }
771
772
773 static void
774 parse_validation_model (const char *model)
775 {
776   int i = gpgsm_parse_validation_model (model);
777   if (i == -1)
778     log_error (_("unknown validation model '%s'\n"), model);
779   else
780     default_validation_model = i;
781 }
782
783
784 /* Release the list of SERVERS.  As usual it is okay to call this
785    function with SERVERS passed as NULL.  */
786 void
787 keyserver_list_free (struct keyserver_spec *servers)
788 {
789   while (servers)
790     {
791       struct keyserver_spec *tmp = servers->next;
792       xfree (servers->host);
793       xfree (servers->user);
794       if (servers->pass)
795         memset (servers->pass, 0, strlen (servers->pass));
796       xfree (servers->pass);
797       xfree (servers->base);
798       xfree (servers);
799       servers = tmp;
800     }
801 }
802
803 /* See also dirmngr ldapserver_parse_one().  */
804 struct keyserver_spec *
805 parse_keyserver_line (char *line,
806                       const char *filename, unsigned int lineno)
807 {
808   char *p;
809   char *endp;
810   struct keyserver_spec *server;
811   int fieldno;
812   int fail = 0;
813
814   /* Parse the colon separated fields.  */
815   server = xcalloc (1, sizeof *server);
816   for (fieldno = 1, p = line; p; p = endp, fieldno++ )
817     {
818       endp = strchr (p, ':');
819       if (endp)
820         *endp++ = '\0';
821       trim_spaces (p);
822       switch (fieldno)
823         {
824         case 1:
825           if (*p)
826             server->host = xstrdup (p);
827           else
828             {
829               log_error (_("%s:%u: no hostname given\n"),
830                          filename, lineno);
831               fail = 1;
832             }
833           break;
834
835         case 2:
836           if (*p)
837             server->port = atoi (p);
838           break;
839
840         case 3:
841           if (*p)
842             server->user = xstrdup (p);
843           break;
844
845         case 4:
846           if (*p && !server->user)
847             {
848               log_error (_("%s:%u: password given without user\n"),
849                          filename, lineno);
850               fail = 1;
851             }
852           else if (*p)
853             server->pass = xstrdup (p);
854           break;
855
856         case 5:
857           if (*p)
858             server->base = xstrdup (p);
859           break;
860
861         default:
862           /* (We silently ignore extra fields.) */
863           break;
864         }
865     }
866
867   if (fail)
868     {
869       log_info (_("%s:%u: skipping this line\n"), filename, lineno);
870       keyserver_list_free (server);
871       server = NULL;
872     }
873
874   return server;
875 }
876
877
878 int
879 main ( int argc, char **argv)
880 {
881   ARGPARSE_ARGS pargs;
882   int orig_argc;
883   char **orig_argv;
884   /*  char *username;*/
885   int may_coredump;
886   strlist_t sl, remusr= NULL, locusr=NULL;
887   strlist_t nrings=NULL;
888   int detached_sig = 0;
889   FILE *configfp = NULL;
890   char *configname = NULL;
891   unsigned configlineno;
892   int parse_debug = 0;
893   int no_more_options = 0;
894   int default_config =1;
895   int default_keyring = 1;
896   char *logfile = NULL;
897   char *auditlog = NULL;
898   char *htmlauditlog = NULL;
899   int greeting = 0;
900   int nogreeting = 0;
901   int debug_wait = 0;
902   int use_random_seed = 1;
903   int no_common_certs_import = 0;
904   int with_fpr = 0;
905   const char *forced_digest_algo = NULL;
906   const char *extra_digest_algo = NULL;
907   enum cmd_and_opt_values cmd = 0;
908   struct server_control_s ctrl;
909   certlist_t recplist = NULL;
910   certlist_t signerlist = NULL;
911   int do_not_setup_keys = 0;
912   int recp_required = 0;
913   estream_t auditfp = NULL;
914   estream_t htmlauditfp = NULL;
915   struct assuan_malloc_hooks malloc_hooks;
916   int pwfd = -1;
917   /*mtrace();*/
918
919   early_system_init ();
920   gnupg_reopen_std (GPGSM_NAME);
921   /* trap_unaligned ();*/
922   gnupg_rl_initialize ();
923   set_strusage (my_strusage);
924   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
925
926   /* Please note that we may running SUID(ROOT), so be very CAREFUL
927      when adding any stuff between here and the call to secmem_init()
928      somewhere after the option parsing */
929   log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
930
931   /* Make sure that our subsystems are ready.  */
932   i18n_init ();
933   init_common_subsystems (&argc, &argv);
934
935   /* Check that the libraries are suitable.  Do it here because the
936      option parse may need services of the library */
937   if (!ksba_check_version (NEED_KSBA_VERSION) )
938     log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
939                NEED_KSBA_VERSION, ksba_check_version (NULL) );
940
941
942   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
943
944   may_coredump = disable_core_dumps ();
945
946   gnupg_init_signals (0, emergency_cleanup);
947
948   dotlock_create (NULL, 0); /* Register lockfile cleanup.  */
949
950   /* Tell the compliance module who we are.  */
951   gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPGSM);
952
953   opt.autostart = 1;
954   opt.session_env = session_env_new ();
955   if (!opt.session_env)
956     log_fatal ("error allocating session environment block: %s\n",
957                strerror (errno));
958
959   /* Note: If you change this default cipher algorithm , please
960      remember to update the Gpgconflist entry as well.  */
961   opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
962
963
964   /* First check whether we have a config file on the commandline */
965   orig_argc = argc;
966   orig_argv = argv;
967   pargs.argc = &argc;
968   pargs.argv = &argv;
969   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
970   while (arg_parse( &pargs, opts))
971     {
972       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
973         parse_debug++;
974       else if (pargs.r_opt == oOptions)
975         { /* yes there is one, so we do not try the default one but
976              read the config file when it is encountered at the
977              commandline */
978           default_config = 0;
979         }
980       else if (pargs.r_opt == oNoOptions)
981         {
982           default_config = 0; /* --no-options */
983           opt.no_homedir_creation = 1;
984         }
985       else if (pargs.r_opt == oHomedir)
986         gnupg_set_homedir (pargs.r.ret_str);
987       else if (pargs.r_opt == aCallProtectTool)
988         break; /* This break makes sure that --version and --help are
989                   passed to the protect-tool. */
990     }
991
992
993   /* Initialize the secure memory. */
994   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
995   maybe_setuid = 0;
996
997   /*
998      Now we are now working under our real uid
999   */
1000
1001   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
1002
1003   malloc_hooks.malloc = gcry_malloc;
1004   malloc_hooks.realloc = gcry_realloc;
1005   malloc_hooks.free = gcry_free;
1006   assuan_set_malloc_hooks (&malloc_hooks);
1007   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1008   setup_libassuan_logging (&opt.debug, NULL);
1009
1010   keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1011
1012   /* Setup a default control structure for command line mode */
1013   memset (&ctrl, 0, sizeof ctrl);
1014   gpgsm_init_default_ctrl (&ctrl);
1015   ctrl.no_server = 1;
1016   ctrl.status_fd = -1; /* No status output. */
1017   ctrl.autodetect_encoding = 1;
1018
1019   /* Set the default option file */
1020   if (default_config )
1021     configname = make_filename (gnupg_homedir (),
1022                                 GPGSM_NAME EXTSEP_S "conf", NULL);
1023   /* Set the default policy file */
1024   opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
1025
1026   argc        = orig_argc;
1027   argv        = orig_argv;
1028   pargs.argc  = &argc;
1029   pargs.argv  = &argv;
1030   pargs.flags =  1;  /* do not remove the args */
1031
1032  next_pass:
1033   if (configname) {
1034     configlineno = 0;
1035     configfp = fopen (configname, "r");
1036     if (!configfp)
1037       {
1038         if (default_config)
1039           {
1040             if (parse_debug)
1041               log_info (_("Note: no default option file '%s'\n"), configname);
1042           }
1043         else
1044           {
1045             log_error (_("option file '%s': %s\n"), configname, strerror(errno));
1046             gpgsm_exit(2);
1047           }
1048         xfree(configname);
1049         configname = NULL;
1050       }
1051     if (parse_debug && configname)
1052       log_info (_("reading options from '%s'\n"), configname);
1053     default_config = 0;
1054   }
1055
1056   while (!no_more_options
1057          && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1058     {
1059       switch (pargs.r_opt)
1060         {
1061         case aGPGConfList:
1062         case aGPGConfTest:
1063           set_cmd (&cmd, pargs.r_opt);
1064           do_not_setup_keys = 1;
1065           nogreeting = 1;
1066           break;
1067
1068         case aServer:
1069           opt.batch = 1;
1070           set_cmd (&cmd, aServer);
1071           break;
1072
1073         case aCallDirmngr:
1074           opt.batch = 1;
1075           set_cmd (&cmd, aCallDirmngr);
1076           do_not_setup_keys = 1;
1077           break;
1078
1079         case aCallProtectTool:
1080           opt.batch = 1;
1081           set_cmd (&cmd, aCallProtectTool);
1082           no_more_options = 1; /* Stop parsing. */
1083           do_not_setup_keys = 1;
1084           break;
1085
1086         case aDeleteKey:
1087           set_cmd (&cmd, aDeleteKey);
1088           /*greeting=1;*/
1089           do_not_setup_keys = 1;
1090           break;
1091
1092         case aDetachedSign:
1093           detached_sig = 1;
1094           set_cmd (&cmd, aSign );
1095           break;
1096
1097         case aKeygen:
1098           set_cmd (&cmd, aKeygen);
1099           greeting=1;
1100           do_not_setup_keys = 1;
1101           break;
1102
1103         case aImport:
1104         case aSendKeys:
1105         case aRecvKeys:
1106         case aExport:
1107         case aExportSecretKeyP12:
1108         case aExportSecretKeyP8:
1109         case aExportSecretKeyRaw:
1110         case aDumpKeys:
1111         case aDumpChain:
1112         case aDumpExternalKeys:
1113         case aDumpSecretKeys:
1114         case aListKeys:
1115         case aListExternalKeys:
1116         case aListSecretKeys:
1117         case aListChain:
1118         case aLearnCard:
1119         case aPasswd:
1120         case aKeydbClearSomeCertFlags:
1121           do_not_setup_keys = 1;
1122           set_cmd (&cmd, pargs.r_opt);
1123           break;
1124
1125         case aEncr:
1126           recp_required = 1;
1127           set_cmd (&cmd, pargs.r_opt);
1128           break;
1129
1130         case aSym:
1131         case aDecrypt:
1132         case aSign:
1133         case aClearsign:
1134         case aVerify:
1135           set_cmd (&cmd, pargs.r_opt);
1136           break;
1137
1138           /* Output encoding selection.  */
1139         case oArmor:
1140           ctrl.create_pem = 1;
1141           break;
1142         case oBase64:
1143           ctrl.create_pem = 0;
1144           ctrl.create_base64 = 1;
1145           break;
1146         case oNoArmor:
1147           ctrl.create_pem = 0;
1148           ctrl.create_base64 = 0;
1149           break;
1150
1151         case oP12Charset:
1152           opt.p12_charset = pargs.r.ret_str;
1153           break;
1154
1155         case oPassphraseFD:
1156           pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
1157           break;
1158
1159         case oPinentryMode:
1160           opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
1161           if (opt.pinentry_mode == -1)
1162             log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
1163           break;
1164
1165           /* Input encoding selection.  */
1166         case oAssumeArmor:
1167           ctrl.autodetect_encoding = 0;
1168           ctrl.is_pem = 1;
1169           ctrl.is_base64 = 0;
1170           break;
1171         case oAssumeBase64:
1172           ctrl.autodetect_encoding = 0;
1173           ctrl.is_pem = 0;
1174           ctrl.is_base64 = 1;
1175           break;
1176         case oAssumeBinary:
1177           ctrl.autodetect_encoding = 0;
1178           ctrl.is_pem = 0;
1179           ctrl.is_base64 = 0;
1180           break;
1181
1182         case oDisableCRLChecks:
1183           opt.no_crl_check = 1;
1184           break;
1185         case oEnableCRLChecks:
1186           opt.no_crl_check = 0;
1187           break;
1188         case oDisableTrustedCertCRLCheck:
1189           opt.no_trusted_cert_crl_check = 1;
1190           break;
1191         case oEnableTrustedCertCRLCheck:
1192           opt.no_trusted_cert_crl_check = 0;
1193           break;
1194         case oForceCRLRefresh:
1195           opt.force_crl_refresh = 1;
1196           break;
1197
1198         case oDisableOCSP:
1199           ctrl.use_ocsp = opt.enable_ocsp = 0;
1200           break;
1201         case oEnableOCSP:
1202           ctrl.use_ocsp = opt.enable_ocsp = 1;
1203           break;
1204
1205         case oIncludeCerts:
1206           ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1207           break;
1208
1209         case oPolicyFile:
1210           xfree (opt.policy_file);
1211           if (*pargs.r.ret_str)
1212             opt.policy_file = xstrdup (pargs.r.ret_str);
1213           else
1214             opt.policy_file = NULL;
1215           break;
1216
1217         case oDisablePolicyChecks:
1218           opt.no_policy_check = 1;
1219           break;
1220         case oEnablePolicyChecks:
1221           opt.no_policy_check = 0;
1222           break;
1223
1224         case oAutoIssuerKeyRetrieve:
1225           opt.auto_issuer_key_retrieve = 1;
1226           break;
1227
1228         case oOutput: opt.outfile = pargs.r.ret_str; break;
1229
1230
1231         case oQuiet: opt.quiet = 1; break;
1232         case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1233         case oDryRun: opt.dry_run = 1; break;
1234
1235         case oVerbose:
1236           opt.verbose++;
1237           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1238           break;
1239         case oNoVerbose:
1240           opt.verbose = 0;
1241           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1242           break;
1243
1244         case oLogFile: logfile = pargs.r.ret_str; break;
1245         case oNoLogFile: logfile = NULL; break;
1246
1247         case oAuditLog: auditlog = pargs.r.ret_str; break;
1248         case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1249
1250         case oBatch:
1251           opt.batch = 1;
1252           greeting = 0;
1253           break;
1254         case oNoBatch: opt.batch = 0; break;
1255
1256         case oAnswerYes: opt.answer_yes = 1; break;
1257         case oAnswerNo: opt.answer_no = 1; break;
1258
1259         case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1260
1261         case oDebug:
1262           if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
1263             {
1264               pargs.r_opt = ARGPARSE_INVALID_ARG;
1265               pargs.err = ARGPARSE_PRINT_ERROR;
1266             }
1267           break;
1268         case oDebugAll: debug_value = ~0; break;
1269         case oDebugNone: debug_value = 0; break;
1270         case oDebugLevel: debug_level = pargs.r.ret_str; break;
1271         case oDebugWait: debug_wait = pargs.r.ret_int; break;
1272         case oDebugAllowCoreDump:
1273           may_coredump = enable_core_dumps ();
1274           break;
1275         case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1276         case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1277
1278         case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1279         case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1280         case oWithMD5Fingerprint:
1281           opt.with_md5_fingerprint=1; /*fall through*/
1282         case oWithFingerprint:
1283           with_fpr=1; /*fall through*/
1284         case aFingerprint:
1285           opt.fingerprint++;
1286           break;
1287
1288         case oWithKeygrip:
1289           opt.with_keygrip = 1;
1290           break;
1291
1292         case oOptions:
1293           /* config files may not be nested (silently ignore them) */
1294           if (!configfp)
1295             {
1296               xfree(configname);
1297               configname = xstrdup (pargs.r.ret_str);
1298               goto next_pass;
1299             }
1300           break;
1301         case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
1302         case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
1303         case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
1304
1305         case oDisplay:
1306           set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1307           break;
1308         case oTTYname:
1309           set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1310           break;
1311         case oTTYtype:
1312           set_opt_session_env ("TERM", pargs.r.ret_str);
1313           break;
1314         case oXauthority:
1315           set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1316           break;
1317
1318         case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1319         case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1320
1321         case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str;  break;
1322         case oDisableDirmngr: opt.disable_dirmngr = 1;  break;
1323         case oPreferSystemDirmngr: /* Obsolete */; break;
1324         case oProtectToolProgram:
1325           opt.protect_tool_program = pargs.r.ret_str;
1326           break;
1327
1328         case oFakedSystemTime:
1329           {
1330             time_t faked_time = isotime2epoch (pargs.r.ret_str);
1331             if (faked_time == (time_t)(-1))
1332               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1333             gnupg_set_time (faked_time, 0);
1334           }
1335           break;
1336
1337         case oNoDefKeyring: default_keyring = 0; break;
1338         case oNoGreeting: nogreeting = 1; break;
1339
1340         case oDefaultKey:
1341           if (*pargs.r.ret_str)
1342             {
1343               xfree (opt.local_user);
1344               opt.local_user = xstrdup (pargs.r.ret_str);
1345             }
1346           break;
1347         case oDefRecipient:
1348           if (*pargs.r.ret_str)
1349             opt.def_recipient = xstrdup (pargs.r.ret_str);
1350           break;
1351         case oDefRecipientSelf:
1352           xfree (opt.def_recipient);
1353           opt.def_recipient = NULL;
1354           opt.def_recipient_self = 1;
1355           break;
1356         case oNoDefRecipient:
1357           xfree (opt.def_recipient);
1358           opt.def_recipient = NULL;
1359           opt.def_recipient_self = 0;
1360           break;
1361
1362         case oWithKeyData: opt.with_key_data=1; /* fall through */
1363         case oWithColons: ctrl.with_colons = 1; break;
1364         case oWithSecret: ctrl.with_secret = 1; break;
1365         case oWithValidation: ctrl.with_validation=1; break;
1366         case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1367
1368         case oSkipVerify: opt.skip_verify=1; break;
1369
1370         case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1371         case oEncryptTo: /* Store the recipient in the second list */
1372           sl = add_to_strlist (&remusr, pargs.r.ret_str);
1373           sl->flags = 1;
1374           break;
1375
1376         case oRecipient: /* store the recipient */
1377           add_to_strlist ( &remusr, pargs.r.ret_str);
1378           break;
1379
1380         case oUser: /* Store the local users, the first one is the default */
1381           if (!opt.local_user)
1382             opt.local_user = xstrdup (pargs.r.ret_str);
1383           add_to_strlist (&locusr, pargs.r.ret_str);
1384           break;
1385
1386         case oNoSecmemWarn:
1387           gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1388           break;
1389
1390         case oCipherAlgo:
1391           opt.def_cipher_algoid = pargs.r.ret_str;
1392           break;
1393
1394         case oDisableCipherAlgo:
1395           {
1396             int algo = gcry_cipher_map_name (pargs.r.ret_str);
1397             gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1398           }
1399           break;
1400         case oDisablePubkeyAlgo:
1401           {
1402             int algo = gcry_pk_map_name (pargs.r.ret_str);
1403             gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1404           }
1405           break;
1406
1407         case oDigestAlgo:
1408           forced_digest_algo = pargs.r.ret_str;
1409           break;
1410
1411         case oExtraDigestAlgo:
1412           extra_digest_algo = pargs.r.ret_str;
1413           break;
1414
1415         case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1416         case oNoRandomSeedFile: use_random_seed = 0; break;
1417         case oNoCommonCertsImport: no_common_certs_import = 1; break;
1418
1419         case oEnableSpecialFilenames:
1420           enable_special_filenames ();
1421           break;
1422
1423         case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1424
1425         case oKeyServer:
1426           {
1427             struct keyserver_spec *keyserver;
1428             keyserver = parse_keyserver_line (pargs.r.ret_str,
1429                                               configname, configlineno);
1430             if (! keyserver)
1431               log_error (_("could not parse keyserver\n"));
1432             else
1433               {
1434                 /* FIXME: Keep last next pointer.  */
1435                 struct keyserver_spec **next_p = &opt.keyserver;
1436                 while (*next_p)
1437                   next_p = &(*next_p)->next;
1438                 *next_p = keyserver;
1439               }
1440           }
1441           break;
1442
1443         case oIgnoreCertExtension:
1444           add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1445           break;
1446
1447         case oNoAutostart: opt.autostart = 0; break;
1448
1449         case oCompliance:
1450           {
1451             struct gnupg_compliance_option compliance_options[] =
1452               {
1453                 { "de-vs", CO_DE_VS }
1454               };
1455             int compliance = gnupg_parse_compliance_option (pargs.r.ret_str,
1456                                                             compliance_options,
1457                                                             DIM (compliance_options),
1458                                                             opt.quiet);
1459             if (compliance < 0)
1460               gpgsm_exit (1);
1461             opt.compliance = compliance;
1462           }
1463           break;
1464
1465         default:
1466           pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1467           break;
1468         }
1469     }
1470
1471   if (configfp)
1472     {
1473       fclose (configfp);
1474       configfp = NULL;
1475       /* Keep a copy of the config filename. */
1476       opt.config_filename = configname;
1477       configname = NULL;
1478       goto next_pass;
1479     }
1480   xfree (configname);
1481   configname = NULL;
1482
1483   if (!opt.config_filename)
1484     opt.config_filename = make_filename (gnupg_homedir (),
1485                                          GPGSM_NAME EXTSEP_S "conf",
1486                                          NULL);
1487
1488   if (log_get_errorcount(0))
1489     gpgsm_exit(2);
1490
1491   if (pwfd != -1)       /* Read the passphrase now.  */
1492     read_passphrase_from_fd (pwfd);
1493
1494   /* Now that we have the options parsed we need to update the default
1495      control structure.  */
1496   gpgsm_init_default_ctrl (&ctrl);
1497
1498   if (nogreeting)
1499     greeting = 0;
1500
1501   if (greeting)
1502     {
1503       es_fprintf (es_stderr, "%s %s; %s\n",
1504                   strusage(11), strusage(13), strusage(14) );
1505       es_fprintf (es_stderr, "%s\n", strusage(15) );
1506     }
1507 #  ifdef IS_DEVELOPMENT_VERSION
1508   if (!opt.batch)
1509     {
1510       log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1511       log_info ("It is only intended for test purposes and should NOT be\n");
1512       log_info ("used in a production environment or with production keys!\n");
1513     }
1514 #  endif
1515
1516   if (may_coredump && !opt.quiet)
1517     log_info (_("WARNING: program may create a core file!\n"));
1518
1519 /*   if (opt.qualsig_approval && !opt.quiet) */
1520 /*     log_info (_("This software has officially been approved to " */
1521 /*                 "create and verify\n" */
1522 /*                 "qualified signatures according to German law.\n")); */
1523
1524   if (logfile && cmd == aServer)
1525     {
1526       log_set_file (logfile);
1527       log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1528     }
1529
1530   if (gnupg_faked_time_p ())
1531     {
1532       gnupg_isotime_t tbuf;
1533
1534       log_info (_("WARNING: running with faked system time: "));
1535       gnupg_get_isotime (tbuf);
1536       dump_isotime (tbuf);
1537       log_printf ("\n");
1538     }
1539
1540   /* Print a warning if an argument looks like an option.  */
1541   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1542     {
1543       int i;
1544
1545       for (i=0; i < argc; i++)
1546         if (argv[i][0] == '-' && argv[i][1] == '-')
1547           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1548     }
1549
1550 /*FIXME    if (opt.batch) */
1551 /*      tty_batchmode (1); */
1552
1553   gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1554
1555   set_debug ();
1556
1557   /* Although we always use gpgsm_exit, we better install a regualr
1558      exit handler so that at least the secure memory gets wiped
1559      out. */
1560   if (atexit (emergency_cleanup))
1561     {
1562       log_error ("atexit failed\n");
1563       gpgsm_exit (2);
1564     }
1565
1566   /* Must do this after dropping setuid, because the mapping functions
1567      may try to load an module and we may have disabled an algorithm.
1568      We remap the commonly used algorithms to the OIDs for
1569      convenience.  We need to work with the OIDs because they are used
1570      to check whether the encryption mode is actually available. */
1571   if (!strcmp (opt.def_cipher_algoid, "3DES") )
1572     opt.def_cipher_algoid = "1.2.840.113549.3.7";
1573   else if (!strcmp (opt.def_cipher_algoid, "AES")
1574            || !strcmp (opt.def_cipher_algoid, "AES128"))
1575     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1576   else if (!strcmp (opt.def_cipher_algoid, "AES192") )
1577     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
1578   else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1579     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1580   else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1581            || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1582     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1583   else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1584     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1585   else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
1586     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1587   else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1588     opt.def_cipher_algoid = "1.2.410.200004.1.4";
1589   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1590            || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1591     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1592   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1593     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1594   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1595     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1596
1597   if (cmd != aGPGConfList)
1598     {
1599       if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1600            || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1601         log_error (_("selected cipher algorithm is invalid\n"));
1602
1603       if (forced_digest_algo)
1604         {
1605           opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1606           if (our_md_test_algo(opt.forced_digest_algo) )
1607             log_error (_("selected digest algorithm is invalid\n"));
1608         }
1609       if (extra_digest_algo)
1610         {
1611           opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1612           if (our_md_test_algo (opt.extra_digest_algo) )
1613             log_error (_("selected digest algorithm is invalid\n"));
1614         }
1615     }
1616
1617   /* Check our chosen algorithms against the list of allowed
1618    * algorithms in the current compliance mode, and fail hard if it is
1619    * not.  This is us being nice to the user informing her early that
1620    * the chosen algorithms are not available.  We also check and
1621    * enforce this right before the actual operation.  */
1622   if (! gnupg_cipher_is_allowed (opt.compliance,
1623                                  cmd == aEncr || cmd == aSignEncr,
1624                                  gcry_cipher_map_name (opt.def_cipher_algoid),
1625                                  GCRY_CIPHER_MODE_NONE)
1626       && ! gnupg_cipher_is_allowed (opt.compliance,
1627                                     cmd == aEncr || cmd == aSignEncr,
1628                                     gcry_cipher_mode_from_oid
1629                                     (opt.def_cipher_algoid),
1630                                     GCRY_CIPHER_MODE_NONE))
1631     log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
1632                opt.def_cipher_algoid,
1633                gnupg_compliance_option_string (opt.compliance));
1634
1635   if (forced_digest_algo
1636       && ! gnupg_digest_is_allowed (opt.compliance,
1637                                      cmd == aSign
1638                                      || cmd == aSignEncr
1639                                      || cmd == aClearsign,
1640                                      opt.forced_digest_algo))
1641     log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1642                forced_digest_algo,
1643                gnupg_compliance_option_string (opt.compliance));
1644
1645   if (extra_digest_algo
1646       && ! gnupg_digest_is_allowed (opt.compliance,
1647                                      cmd == aSign
1648                                      || cmd == aSignEncr
1649                                      || cmd == aClearsign,
1650                                      opt.extra_digest_algo))
1651     log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
1652                forced_digest_algo,
1653                gnupg_compliance_option_string (opt.compliance));
1654
1655   if (log_get_errorcount(0))
1656     gpgsm_exit(2);
1657
1658   /* Set the random seed file. */
1659   if (use_random_seed)
1660     {
1661       char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
1662       gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1663       xfree(p);
1664     }
1665
1666   if (!cmd && opt.fingerprint && !with_fpr)
1667     set_cmd (&cmd, aListKeys);
1668
1669   /* Add default keybox. */
1670   if (!nrings && default_keyring)
1671     {
1672       int created;
1673
1674       keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
1675       if (created && !no_common_certs_import)
1676         {
1677           /* Import the standard certificates for a new default keybox. */
1678           char *filelist[2];
1679
1680           filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1681           filelist[1] = NULL;
1682           if (!access (filelist[0], F_OK))
1683             {
1684               log_info (_("importing common certificates '%s'\n"),
1685                         filelist[0]);
1686               gpgsm_import_files (&ctrl, 1, filelist, open_read);
1687             }
1688           xfree (filelist[0]);
1689         }
1690     }
1691   for (sl = nrings; sl; sl = sl->next)
1692     keydb_add_resource (&ctrl, sl->d, 0, NULL);
1693   FREE_STRLIST(nrings);
1694
1695
1696   /* Prepare the audit log feature for certain commands.  */
1697   if (auditlog || htmlauditlog)
1698     {
1699       switch (cmd)
1700         {
1701         case aEncr:
1702         case aSign:
1703         case aDecrypt:
1704         case aVerify:
1705           audit_release (ctrl.audit);
1706           ctrl.audit = audit_new ();
1707           if (auditlog)
1708             auditfp = open_es_fwrite (auditlog);
1709           if (htmlauditlog)
1710             htmlauditfp = open_es_fwrite (htmlauditlog);
1711           break;
1712         default:
1713           break;
1714         }
1715     }
1716
1717
1718   if (!do_not_setup_keys)
1719     {
1720       for (sl = locusr; sl ; sl = sl->next)
1721         {
1722           int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1723           if (rc)
1724             {
1725               log_error (_("can't sign using '%s': %s\n"),
1726                          sl->d, gpg_strerror (rc));
1727               gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1728                              get_inv_recpsgnr_code (rc), sl->d, NULL);
1729               gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1730                              get_inv_recpsgnr_code (rc), sl->d, NULL);
1731             }
1732         }
1733
1734       /* Build the recipient list.  We first add the regular ones and then
1735          the encrypt-to ones because the underlying function will silently
1736          ignore duplicates and we can't allow keeping a duplicate which is
1737          flagged as encrypt-to as the actually encrypt function would then
1738          complain about no (regular) recipients. */
1739       for (sl = remusr; sl; sl = sl->next)
1740         if (!(sl->flags & 1))
1741           do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1742       if (!opt.no_encrypt_to)
1743         {
1744           for (sl = remusr; sl; sl = sl->next)
1745             if ((sl->flags & 1))
1746               do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1747         }
1748     }
1749
1750   if (log_get_errorcount(0))
1751     gpgsm_exit(1); /* Must stop for invalid recipients. */
1752
1753   /* Dispatch command.  */
1754   switch (cmd)
1755     {
1756     case aGPGConfList:
1757       { /* List options and default values in the GPG Conf format.  */
1758         char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1759
1760         es_printf ("%s-%s.conf:%lu:\"%s\n",
1761                    GPGCONF_NAME, GPGSM_NAME,
1762                    GC_OPT_FLAG_DEFAULT, config_filename_esc);
1763         xfree (config_filename_esc);
1764
1765         es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1766         es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1767         es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1768         es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1769         es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1770         es_printf ("enable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1771         es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1772         es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1773         es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1774                    DEFAULT_INCLUDE_CERTS);
1775         es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1776         es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1777         es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1778         es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1779                    DEFAULT_CIPHER_ALGO);
1780         es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1781         es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1782         es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1783         es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1784
1785         /* The next one is an info only item and should match what
1786            proc_parameters actually implements.  */
1787         es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1788                    "RSA-2048");
1789
1790       }
1791       break;
1792     case aGPGConfTest:
1793       /* This is merely a dummy command to test whether the
1794          configuration file is valid.  */
1795       break;
1796
1797     case aServer:
1798       if (debug_wait)
1799         {
1800           log_debug ("waiting for debugger - my pid is %u .....\n",
1801                      (unsigned int)getpid());
1802           gnupg_sleep (debug_wait);
1803           log_debug ("... okay\n");
1804          }
1805       gpgsm_server (recplist);
1806       break;
1807
1808     case aCallDirmngr:
1809       if (!argc)
1810         wrong_args ("--call-dirmngr <command> {args}");
1811       else
1812         if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1813           gpgsm_exit (1);
1814       break;
1815
1816     case aCallProtectTool:
1817       run_protect_tool (argc, argv);
1818       break;
1819
1820     case aEncr: /* Encrypt the given file. */
1821       {
1822         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1823
1824         set_binary (stdin);
1825
1826         if (!argc) /* Source is stdin. */
1827           gpgsm_encrypt (&ctrl, recplist, 0, fp);
1828         else if (argc == 1)  /* Source is the given file. */
1829           gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1830         else
1831           wrong_args ("--encrypt [datafile]");
1832
1833         es_fclose (fp);
1834       }
1835       break;
1836
1837     case aSign: /* Sign the given file. */
1838       {
1839         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1840
1841         /* Fixme: We should also allow concatenation of multiple files for
1842            signing because that is what gpg does.*/
1843         set_binary (stdin);
1844         if (!argc) /* Create from stdin. */
1845           gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1846         else if (argc == 1) /* From file. */
1847           gpgsm_sign (&ctrl, signerlist,
1848                       open_read (*argv), detached_sig, fp);
1849         else
1850           wrong_args ("--sign [datafile]");
1851
1852         es_fclose (fp);
1853       }
1854       break;
1855
1856     case aSignEncr: /* sign and encrypt the given file */
1857       log_error ("this command has not yet been implemented\n");
1858       break;
1859
1860     case aClearsign: /* make a clearsig */
1861       log_error ("this command has not yet been implemented\n");
1862       break;
1863
1864     case aVerify:
1865       {
1866         estream_t fp = NULL;
1867
1868         set_binary (stdin);
1869         if (argc == 2 && opt.outfile)
1870           log_info ("option --output ignored for a detached signature\n");
1871         else if (opt.outfile)
1872           fp = open_es_fwrite (opt.outfile);
1873
1874         if (!argc)
1875           gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1876         else if (argc == 1)
1877           gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1878         else if (argc == 2) /* detached signature (sig, detached) */
1879           gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1880         else
1881           wrong_args ("--verify [signature [detached_data]]");
1882
1883         es_fclose (fp);
1884       }
1885       break;
1886
1887     case aDecrypt:
1888       {
1889         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1890
1891         set_binary (stdin);
1892         if (!argc)
1893           gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1894         else if (argc == 1)
1895           gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1896         else
1897           wrong_args ("--decrypt [filename]");
1898
1899         es_fclose (fp);
1900       }
1901       break;
1902
1903     case aDeleteKey:
1904       for (sl=NULL; argc; argc--, argv++)
1905         add_to_strlist (&sl, *argv);
1906       gpgsm_delete (&ctrl, sl);
1907       free_strlist(sl);
1908       break;
1909
1910     case aListChain:
1911     case aDumpChain:
1912        ctrl.with_chain = 1; /* fall through */
1913     case aListKeys:
1914     case aDumpKeys:
1915     case aListExternalKeys:
1916     case aDumpExternalKeys:
1917     case aListSecretKeys:
1918     case aDumpSecretKeys:
1919       {
1920         unsigned int mode;
1921         estream_t fp;
1922
1923         switch (cmd)
1924           {
1925           case aListChain:
1926           case aListKeys:         mode = (0   | 0 | (1<<6)); break;
1927           case aDumpChain:
1928           case aDumpKeys:         mode = (256 | 0 | (1<<6)); break;
1929           case aListExternalKeys: mode = (0   | 0 | (1<<7)); break;
1930           case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1931           case aListSecretKeys:   mode = (0   | 2 | (1<<6)); break;
1932           case aDumpSecretKeys:   mode = (256 | 2 | (1<<6)); break;
1933           default: BUG();
1934           }
1935
1936         fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1937         for (sl=NULL; argc; argc--, argv++)
1938           add_to_strlist (&sl, *argv);
1939         gpgsm_list_keys (&ctrl, sl, fp, mode);
1940         free_strlist(sl);
1941         es_fclose (fp);
1942       }
1943       break;
1944
1945
1946     case aKeygen: /* Generate a key; well kind of. */
1947       {
1948         estream_t fpin = NULL;
1949         estream_t fpout;
1950
1951         if (opt.batch)
1952           {
1953             if (!argc) /* Create from stdin. */
1954               fpin = open_es_fread ("-", "r");
1955             else if (argc == 1) /* From file. */
1956               fpin = open_es_fread (*argv, "r");
1957             else
1958               wrong_args ("--generate-key --batch [parmfile]");
1959           }
1960
1961         fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
1962
1963         if (fpin)
1964           gpgsm_genkey (&ctrl, fpin, fpout);
1965         else
1966           gpgsm_gencertreq_tty (&ctrl, fpout);
1967
1968         es_fclose (fpout);
1969       }
1970       break;
1971
1972
1973     case aImport:
1974       gpgsm_import_files (&ctrl, argc, argv, open_read);
1975       break;
1976
1977     case aExport:
1978       {
1979         estream_t fp;
1980
1981         fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1982         for (sl=NULL; argc; argc--, argv++)
1983           add_to_strlist (&sl, *argv);
1984         gpgsm_export (&ctrl, sl, fp);
1985         free_strlist(sl);
1986         es_fclose (fp);
1987       }
1988       break;
1989
1990     case aExportSecretKeyP12:
1991       {
1992         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1993
1994         if (argc == 1)
1995           gpgsm_p12_export (&ctrl, *argv, fp, 0);
1996         else
1997           wrong_args ("--export-secret-key-p12 KEY-ID");
1998         if (fp != es_stdout)
1999           es_fclose (fp);
2000       }
2001       break;
2002
2003     case aExportSecretKeyP8:
2004       {
2005         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2006
2007         if (argc == 1)
2008           gpgsm_p12_export (&ctrl, *argv, fp, 1);
2009         else
2010           wrong_args ("--export-secret-key-p8 KEY-ID");
2011         if (fp != es_stdout)
2012           es_fclose (fp);
2013       }
2014       break;
2015
2016     case aExportSecretKeyRaw:
2017       {
2018         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
2019
2020         if (argc == 1)
2021           gpgsm_p12_export (&ctrl, *argv, fp, 2);
2022         else
2023           wrong_args ("--export-secret-key-raw KEY-ID");
2024         if (fp != es_stdout)
2025           es_fclose (fp);
2026       }
2027       break;
2028
2029     case aSendKeys:
2030     case aRecvKeys:
2031       log_error ("this command has not yet been implemented\n");
2032       break;
2033
2034
2035     case aLearnCard:
2036       if (argc)
2037         wrong_args ("--learn-card");
2038       else
2039         {
2040           int rc = gpgsm_agent_learn (&ctrl);
2041           if (rc)
2042             log_error ("error learning card: %s\n", gpg_strerror (rc));
2043         }
2044       break;
2045
2046     case aPasswd:
2047       if (argc != 1)
2048         wrong_args ("--change-passphrase <key-Id>");
2049       else
2050         {
2051           int rc;
2052           ksba_cert_t cert = NULL;
2053           char *grip = NULL;
2054
2055           rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert, 0);
2056           if (rc)
2057             ;
2058           else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
2059             rc = gpg_error (GPG_ERR_BUG);
2060           else
2061             {
2062               char *desc = gpgsm_format_keydesc (cert);
2063               rc = gpgsm_agent_passwd (&ctrl, grip, desc);
2064               xfree (desc);
2065             }
2066           if (rc)
2067             log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
2068           xfree (grip);
2069           ksba_cert_release (cert);
2070         }
2071       break;
2072
2073     case aKeydbClearSomeCertFlags:
2074       for (sl=NULL; argc; argc--, argv++)
2075         add_to_strlist (&sl, *argv);
2076       keydb_clear_some_cert_flags (&ctrl, sl);
2077       free_strlist(sl);
2078       break;
2079
2080
2081     default:
2082         log_error (_("invalid command (there is no implicit command)\n"));
2083         break;
2084     }
2085
2086   /* Print the audit result if needed.  */
2087   if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
2088     {
2089       if (auditlog && auditfp)
2090         audit_print_result (ctrl.audit, auditfp, 0);
2091       if (htmlauditlog && htmlauditfp)
2092         audit_print_result (ctrl.audit, htmlauditfp, 1);
2093       audit_release (ctrl.audit);
2094       ctrl.audit = NULL;
2095       es_fclose (auditfp);
2096       es_fclose (htmlauditfp);
2097     }
2098
2099   /* cleanup */
2100   keyserver_list_free (opt.keyserver);
2101   opt.keyserver = NULL;
2102   gpgsm_release_certlist (recplist);
2103   gpgsm_release_certlist (signerlist);
2104   FREE_STRLIST (remusr);
2105   FREE_STRLIST (locusr);
2106   gpgsm_exit(0);
2107   return 8; /*NOTREACHED*/
2108 }
2109
2110 /* Note: This function is used by signal handlers!. */
2111 static void
2112 emergency_cleanup (void)
2113 {
2114   gcry_control (GCRYCTL_TERM_SECMEM );
2115 }
2116
2117
2118 void
2119 gpgsm_exit (int rc)
2120 {
2121   gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
2122   if (opt.debug & DBG_MEMSTAT_VALUE)
2123     {
2124       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
2125       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
2126     }
2127   if (opt.debug)
2128     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
2129   emergency_cleanup ();
2130   rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
2131   exit (rc);
2132 }
2133
2134
2135 void
2136 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
2137 {
2138   ctrl->include_certs = default_include_certs;
2139   ctrl->use_ocsp = opt.enable_ocsp;
2140   ctrl->validation_model = default_validation_model;
2141   ctrl->offline = opt.disable_dirmngr;
2142 }
2143
2144
2145 int
2146 gpgsm_parse_validation_model (const char *model)
2147 {
2148   if (!ascii_strcasecmp (model, "shell") )
2149     return 0;
2150   else if ( !ascii_strcasecmp (model, "chain") )
2151     return 1;
2152   else if ( !ascii_strcasecmp (model, "steed") )
2153     return 2;
2154   else
2155     return -1;
2156 }
2157
2158
2159
2160 /* Open the FILENAME for read and return the file descriptor.  Stop
2161    with an error message in case of problems.  "-" denotes stdin and
2162    if special filenames are allowed the given fd is opened instead.  */
2163 static int
2164 open_read (const char *filename)
2165 {
2166   int fd;
2167
2168   if (filename[0] == '-' && !filename[1])
2169     {
2170       set_binary (stdin);
2171       return 0; /* stdin */
2172     }
2173   fd = check_special_filename (filename, 0, 0);
2174   if (fd != -1)
2175     return fd;
2176   fd = open (filename, O_RDONLY | O_BINARY);
2177   if (fd == -1)
2178     {
2179       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2180       gpgsm_exit (2);
2181     }
2182   return fd;
2183 }
2184
2185 /* Same as open_read but return an estream_t.  */
2186 static estream_t
2187 open_es_fread (const char *filename, const char *mode)
2188 {
2189   int fd;
2190   estream_t fp;
2191
2192   if (filename[0] == '-' && !filename[1])
2193     fd = fileno (stdin);
2194   else
2195     fd = check_special_filename (filename, 0, 0);
2196   if (fd != -1)
2197     {
2198       fp = es_fdopen_nc (fd, mode);
2199       if (!fp)
2200         {
2201           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2202           gpgsm_exit (2);
2203         }
2204       return fp;
2205     }
2206   fp = es_fopen (filename, mode);
2207   if (!fp)
2208     {
2209       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2210       gpgsm_exit (2);
2211     }
2212   return fp;
2213 }
2214
2215
2216 /* Open FILENAME for fwrite and return an extended stream.  Stop with
2217    an error message in case of problems.  "-" denotes stdout and if
2218    special filenames are allowed the given fd is opened instead.
2219    Caller must close the returned stream. */
2220 static estream_t
2221 open_es_fwrite (const char *filename)
2222 {
2223   int fd;
2224   estream_t fp;
2225
2226   if (filename[0] == '-' && !filename[1])
2227     {
2228       fflush (stdout);
2229       fp = es_fdopen_nc (fileno(stdout), "wb");
2230       return fp;
2231     }
2232
2233   fd = check_special_filename (filename, 1, 0);
2234   if (fd != -1)
2235     {
2236       fp = es_fdopen_nc (fd, "wb");
2237       if (!fp)
2238         {
2239           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2240           gpgsm_exit (2);
2241         }
2242       return fp;
2243     }
2244   fp = es_fopen (filename, "wb");
2245   if (!fp)
2246     {
2247       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
2248       gpgsm_exit (2);
2249     }
2250   return fp;
2251 }
2252
2253
2254 static void
2255 run_protect_tool (int argc, char **argv)
2256 {
2257 #ifdef HAVE_W32_SYSTEM
2258   (void)argc;
2259   (void)argv;
2260 #else
2261   const char *pgm;
2262   char **av;
2263   int i;
2264
2265   if (!opt.protect_tool_program || !*opt.protect_tool_program)
2266     pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2267   else
2268     pgm = opt.protect_tool_program;
2269
2270   av = xcalloc (argc+2, sizeof *av);
2271   av[0] = strrchr (pgm, '/');
2272   if (!av[0])
2273     av[0] = xstrdup (pgm);
2274   for (i=1; argc; i++, argc--, argv++)
2275     av[i] = *argv;
2276   av[i] = NULL;
2277   execv (pgm, av);
2278   log_error ("error executing '%s': %s\n", pgm, strerror (errno));
2279 #endif /*!HAVE_W32_SYSTEM*/
2280   gpgsm_exit (2);
2281 }