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