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