484ce9d313f9d6fc1bea6597284e6d7954fc952e
[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         default_config = 0; /* --no-options */
955       else if (pargs.r_opt == oHomedir)
956         opt.homedir = pargs.r.ret_str;
957       else if (pargs.r_opt == aCallProtectTool)
958         break; /* This break makes sure that --version and --help are
959                   passed to the protect-tool. */
960     }
961
962
963   /* Initialize the secure memory. */
964   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
965   maybe_setuid = 0;
966
967   /*
968      Now we are now working under our real uid
969   */
970
971   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
972
973   malloc_hooks.malloc = gcry_malloc;
974   malloc_hooks.realloc = gcry_realloc;
975   malloc_hooks.free = gcry_free;
976   assuan_set_malloc_hooks (&malloc_hooks);
977   assuan_set_assuan_log_prefix (log_get_prefix (NULL));
978   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
979
980   keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
981
982   /* Setup a default control structure for command line mode */
983   memset (&ctrl, 0, sizeof ctrl);
984   gpgsm_init_default_ctrl (&ctrl);
985   ctrl.no_server = 1;
986   ctrl.status_fd = -1; /* No status output. */
987   ctrl.autodetect_encoding = 1;
988
989   /* Set the default option file */
990   if (default_config )
991     configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
992   /* Set the default policy file */
993   opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
994
995   argc        = orig_argc;
996   argv        = orig_argv;
997   pargs.argc  = &argc;
998   pargs.argv  = &argv;
999   pargs.flags =  1;  /* do not remove the args */
1000
1001  next_pass:
1002   if (configname) {
1003     configlineno = 0;
1004     configfp = fopen (configname, "r");
1005     if (!configfp)
1006       {
1007         if (default_config)
1008           {
1009             if (parse_debug)
1010               log_info (_("NOTE: no default option file `%s'\n"), configname);
1011           }
1012         else
1013           {
1014             log_error (_("option file `%s': %s\n"), configname, strerror(errno));
1015             gpgsm_exit(2);
1016           }
1017         xfree(configname);
1018         configname = NULL;
1019       }
1020     if (parse_debug && configname)
1021       log_info (_("reading options from `%s'\n"), configname);
1022     default_config = 0;
1023   }
1024
1025   while (!no_more_options
1026          && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1027     {
1028       switch (pargs.r_opt)
1029         {
1030         case aGPGConfList:
1031         case aGPGConfTest:
1032           set_cmd (&cmd, pargs.r_opt);
1033           do_not_setup_keys = 1;
1034           nogreeting = 1;
1035           break;
1036
1037         case aServer:
1038           opt.batch = 1;
1039           set_cmd (&cmd, aServer);
1040           break;
1041
1042         case aCallDirmngr:
1043           opt.batch = 1;
1044           set_cmd (&cmd, aCallDirmngr);
1045           do_not_setup_keys = 1;
1046           break;
1047
1048         case aCallProtectTool:
1049           opt.batch = 1;
1050           set_cmd (&cmd, aCallProtectTool);
1051           no_more_options = 1; /* Stop parsing. */
1052           do_not_setup_keys = 1;
1053           break;
1054
1055         case aDeleteKey:
1056           set_cmd (&cmd, aDeleteKey);
1057           /*greeting=1;*/
1058           do_not_setup_keys = 1;
1059           break;
1060
1061         case aDetachedSign:
1062           detached_sig = 1;
1063           set_cmd (&cmd, aSign );
1064           break;
1065
1066         case aKeygen:
1067           set_cmd (&cmd, aKeygen);
1068           greeting=1;
1069           do_not_setup_keys = 1;
1070           break;
1071
1072         case aImport:
1073         case aSendKeys:
1074         case aRecvKeys:
1075         case aExport:
1076         case aExportSecretKeyP12:
1077         case aDumpKeys:
1078         case aDumpChain:
1079         case aDumpExternalKeys:
1080         case aDumpSecretKeys:
1081         case aListKeys:
1082         case aListExternalKeys:
1083         case aListSecretKeys:
1084         case aListChain:
1085         case aLearnCard:
1086         case aPasswd:
1087         case aKeydbClearSomeCertFlags:
1088           do_not_setup_keys = 1;
1089           set_cmd (&cmd, pargs.r_opt);
1090           break;
1091
1092         case aEncr:
1093           recp_required = 1;
1094           set_cmd (&cmd, pargs.r_opt);
1095           break;
1096
1097         case aSym:
1098         case aDecrypt:
1099         case aSign:
1100         case aClearsign:
1101         case aVerify:
1102           set_cmd (&cmd, pargs.r_opt);
1103           break;
1104
1105           /* Output encoding selection.  */
1106         case oArmor:
1107           ctrl.create_pem = 1;
1108           break;
1109         case oBase64:
1110           ctrl.create_pem = 0;
1111           ctrl.create_base64 = 1;
1112           break;
1113         case oNoArmor:
1114           ctrl.create_pem = 0;
1115           ctrl.create_base64 = 0;
1116           break;
1117
1118         case oP12Charset:
1119           opt.p12_charset = pargs.r.ret_str;
1120           break;
1121
1122           /* Input encoding selection.  */
1123         case oAssumeArmor:
1124           ctrl.autodetect_encoding = 0;
1125           ctrl.is_pem = 1;
1126           ctrl.is_base64 = 0;
1127           break;
1128         case oAssumeBase64:
1129           ctrl.autodetect_encoding = 0;
1130           ctrl.is_pem = 0;
1131           ctrl.is_base64 = 1;
1132           break;
1133         case oAssumeBinary:
1134           ctrl.autodetect_encoding = 0;
1135           ctrl.is_pem = 0;
1136           ctrl.is_base64 = 0;
1137           break;
1138
1139         case oDisableCRLChecks:
1140           opt.no_crl_check = 1;
1141           break;
1142         case oEnableCRLChecks:
1143           opt.no_crl_check = 0;
1144           break;
1145         case oDisableTrustedCertCRLCheck:
1146           opt.no_trusted_cert_crl_check = 1;
1147           break;
1148         case oEnableTrustedCertCRLCheck:
1149           opt.no_trusted_cert_crl_check = 0;
1150           break;
1151         case oForceCRLRefresh:
1152           opt.force_crl_refresh = 1;
1153           break;
1154
1155         case oDisableOCSP:
1156           ctrl.use_ocsp = opt.enable_ocsp = 0;
1157           break;
1158         case oEnableOCSP:
1159           ctrl.use_ocsp = opt.enable_ocsp = 1;
1160           break;
1161
1162         case oIncludeCerts:
1163           ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1164           break;
1165
1166         case oPolicyFile:
1167           xfree (opt.policy_file);
1168           if (*pargs.r.ret_str)
1169             opt.policy_file = xstrdup (pargs.r.ret_str);
1170           else
1171             opt.policy_file = NULL;
1172           break;
1173
1174         case oDisablePolicyChecks:
1175           opt.no_policy_check = 1;
1176           break;
1177         case oEnablePolicyChecks:
1178           opt.no_policy_check = 0;
1179           break;
1180
1181         case oAutoIssuerKeyRetrieve:
1182           opt.auto_issuer_key_retrieve = 1;
1183           break;
1184
1185         case oOutput: opt.outfile = pargs.r.ret_str; break;
1186
1187
1188         case oQuiet: opt.quiet = 1; break;
1189         case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1190         case oDryRun: opt.dry_run = 1; break;
1191
1192         case oVerbose:
1193           opt.verbose++;
1194           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1195           break;
1196         case oNoVerbose:
1197           opt.verbose = 0;
1198           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1199           break;
1200
1201         case oLogFile: logfile = pargs.r.ret_str; break;
1202         case oNoLogFile: logfile = NULL; break;
1203
1204         case oAuditLog: auditlog = pargs.r.ret_str; break;
1205         case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
1206
1207         case oBatch:
1208           opt.batch = 1;
1209           greeting = 0;
1210           break;
1211         case oNoBatch: opt.batch = 0; break;
1212
1213         case oAnswerYes: opt.answer_yes = 1; break;
1214         case oAnswerNo: opt.answer_no = 1; break;
1215
1216         case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1217
1218         case oDebug: debug_value |= pargs.r.ret_ulong; break;
1219         case oDebugAll: debug_value = ~0; break;
1220         case oDebugNone: debug_value = 0; break;
1221         case oDebugLevel: debug_level = pargs.r.ret_str; break;
1222         case oDebugWait: debug_wait = pargs.r.ret_int; break;
1223         case oDebugAllowCoreDump:
1224           may_coredump = enable_core_dumps ();
1225           break;
1226         case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1227         case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1228         case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1229
1230         case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1231         case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1232         case oWithMD5Fingerprint:
1233           opt.with_md5_fingerprint=1; /*fall thru*/
1234         case oWithFingerprint:
1235           with_fpr=1; /*fall thru*/
1236         case aFingerprint:
1237           opt.fingerprint++;
1238           break;
1239
1240         case oOptions:
1241           /* config files may not be nested (silently ignore them) */
1242           if (!configfp)
1243             {
1244               xfree(configname);
1245               configname = xstrdup (pargs.r.ret_str);
1246               goto next_pass;
1247             }
1248           break;
1249         case oNoOptions: break; /* no-options */
1250         case oHomedir: opt.homedir = pargs.r.ret_str; break;
1251         case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
1252
1253         case oDisplay:
1254           set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1255           break;
1256         case oTTYname:
1257           set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1258           break;
1259         case oTTYtype:
1260           set_opt_session_env ("TERM", pargs.r.ret_str);
1261           break;
1262         case oXauthority:
1263           set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1264           break;
1265
1266         case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1267         case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1268
1269         case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str;  break;
1270         case oDisableDirmngr: opt.disable_dirmngr = 1;  break;
1271         case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1272         case oProtectToolProgram:
1273           opt.protect_tool_program = pargs.r.ret_str;
1274           break;
1275
1276         case oFakedSystemTime:
1277           {
1278             time_t faked_time = isotime2epoch (pargs.r.ret_str);
1279             if (faked_time == (time_t)(-1))
1280               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1281             gnupg_set_time (faked_time, 0);
1282           }
1283           break;
1284
1285         case oNoDefKeyring: default_keyring = 0; break;
1286         case oNoGreeting: nogreeting = 1; break;
1287
1288         case oDefaultKey:
1289           if (*pargs.r.ret_str)
1290             {
1291               xfree (opt.local_user);
1292               opt.local_user = xstrdup (pargs.r.ret_str);
1293             }
1294           break;
1295         case oDefRecipient:
1296           if (*pargs.r.ret_str)
1297             opt.def_recipient = xstrdup (pargs.r.ret_str);
1298           break;
1299         case oDefRecipientSelf:
1300           xfree (opt.def_recipient);
1301           opt.def_recipient = NULL;
1302           opt.def_recipient_self = 1;
1303           break;
1304         case oNoDefRecipient:
1305           xfree (opt.def_recipient);
1306           opt.def_recipient = NULL;
1307           opt.def_recipient_self = 0;
1308           break;
1309
1310         case oWithKeyData: opt.with_key_data=1; /* fall thru */
1311         case oWithColons: ctrl.with_colons = 1; break;
1312         case oWithValidation: ctrl.with_validation=1; break;
1313         case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1314
1315         case oSkipVerify: opt.skip_verify=1; break;
1316
1317         case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1318         case oEncryptTo: /* Store the recipient in the second list */
1319           sl = add_to_strlist (&remusr, pargs.r.ret_str);
1320           sl->flags = 1;
1321           break;
1322
1323         case oRecipient: /* store the recipient */
1324           add_to_strlist ( &remusr, pargs.r.ret_str);
1325           break;
1326
1327         case oUser: /* Store the local users, the first one is the default */
1328           if (!opt.local_user)
1329             opt.local_user = xstrdup (pargs.r.ret_str);
1330           add_to_strlist (&locusr, pargs.r.ret_str);
1331           break;
1332
1333         case oNoSecmemWarn:
1334           gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1335           break;
1336
1337         case oCipherAlgo:
1338           opt.def_cipher_algoid = pargs.r.ret_str;
1339           break;
1340
1341         case oDisableCipherAlgo:
1342           {
1343             int algo = gcry_cipher_map_name (pargs.r.ret_str);
1344             gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1345           }
1346           break;
1347         case oDisablePubkeyAlgo:
1348           {
1349             int algo = gcry_pk_map_name (pargs.r.ret_str);
1350             gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1351           }
1352           break;
1353
1354         case oDigestAlgo:
1355           forced_digest_algo = pargs.r.ret_str;
1356           break;
1357
1358         case oExtraDigestAlgo:
1359           extra_digest_algo = pargs.r.ret_str;
1360           break;
1361
1362         case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1363         case oNoRandomSeedFile: use_random_seed = 0; break;
1364         case oNoCommonCertsImport: no_common_certs_import = 1; break;
1365
1366         case oEnableSpecialFilenames: allow_special_filenames =1; break;
1367
1368         case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1369
1370         case oKeyServer:
1371           {
1372             struct keyserver_spec *keyserver;
1373             keyserver = parse_keyserver_line (pargs.r.ret_str,
1374                                               configname, configlineno);
1375             if (! keyserver)
1376               log_error (_("could not parse keyserver\n"));
1377             else
1378               {
1379                 /* FIXME: Keep last next pointer.  */
1380                 struct keyserver_spec **next_p = &opt.keyserver;
1381                 while (*next_p)
1382                   next_p = &(*next_p)->next;
1383                 *next_p = keyserver;
1384               }
1385           }
1386           break;
1387
1388         case oIgnoreCertExtension:
1389           add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
1390           break;
1391
1392         default:
1393           pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1394           break;
1395         }
1396     }
1397
1398   if (configfp)
1399     {
1400       fclose (configfp);
1401       configfp = NULL;
1402       /* Keep a copy of the config filename. */
1403       opt.config_filename = configname;
1404       configname = NULL;
1405       goto next_pass;
1406     }
1407   xfree (configname);
1408   configname = NULL;
1409
1410   if (!opt.config_filename)
1411     opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1412
1413   if (log_get_errorcount(0))
1414     gpgsm_exit(2);
1415
1416   /* Now that we have the options parsed we need to update the default
1417      control structure.  */
1418   gpgsm_init_default_ctrl (&ctrl);
1419
1420   if (nogreeting)
1421     greeting = 0;
1422
1423   if (greeting)
1424     {
1425       fprintf(stderr, "%s %s; %s\n",
1426               strusage(11), strusage(13), strusage(14) );
1427       fprintf(stderr, "%s\n", strusage(15) );
1428     }
1429 #  ifdef IS_DEVELOPMENT_VERSION
1430   if (!opt.batch)
1431     {
1432       log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1433       log_info ("It is only intended for test purposes and should NOT be\n");
1434       log_info ("used in a production environment or with production keys!\n");
1435     }
1436 #  endif
1437
1438   if (may_coredump && !opt.quiet)
1439     log_info (_("WARNING: program may create a core file!\n"));
1440
1441 /*   if (opt.qualsig_approval && !opt.quiet) */
1442 /*     log_info (_("This software has offically been approved to " */
1443 /*                 "create and verify\n" */
1444 /*                 "qualified signatures according to German law.\n")); */
1445
1446   if (logfile && cmd == aServer)
1447     {
1448       log_set_file (logfile);
1449       log_set_prefix (NULL, 1|2|4);
1450     }
1451
1452   if (gnupg_faked_time_p ())
1453     {
1454       gnupg_isotime_t tbuf;
1455
1456       log_info (_("WARNING: running with faked system time: "));
1457       gnupg_get_isotime (tbuf);
1458       dump_isotime (tbuf);
1459       log_printf ("\n");
1460     }
1461
1462 /*FIXME    if (opt.batch) */
1463 /*      tty_batchmode (1); */
1464
1465   gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1466
1467   set_debug ();
1468
1469   /* Although we alwasy use gpgsm_exit, we better install a regualr
1470      exit handler so that at least the secure memory gets wiped
1471      out. */
1472   if (atexit (emergency_cleanup))
1473     {
1474       log_error ("atexit failed\n");
1475       gpgsm_exit (2);
1476     }
1477
1478   /* Must do this after dropping setuid, because the mapping functions
1479      may try to load an module and we may have disabled an algorithm.
1480      We remap the commonly used algorithms to the OIDs for
1481      convenience.  We need to work with the OIDs because they are used
1482      to check whether the encryption mode is actually available. */
1483   if (!strcmp (opt.def_cipher_algoid, "3DES") )
1484     opt.def_cipher_algoid = "1.2.840.113549.3.7";
1485   else if (!strcmp (opt.def_cipher_algoid, "AES")
1486            || !strcmp (opt.def_cipher_algoid, "AES128"))
1487     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1488   else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1489     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1490   else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1491            || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1492     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1493   else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1494     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1495   else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1496     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1497   else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1498     opt.def_cipher_algoid = "1.2.410.200004.1.4";
1499   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1500            || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1501     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1502   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1503     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1504   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1505     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1506
1507   if (cmd != aGPGConfList)
1508     {
1509       if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1510            || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1511         log_error (_("selected cipher algorithm is invalid\n"));
1512
1513       if (forced_digest_algo)
1514         {
1515           opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1516           if (our_md_test_algo(opt.forced_digest_algo) )
1517             log_error (_("selected digest algorithm is invalid\n"));
1518         }
1519       if (extra_digest_algo)
1520         {
1521           opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1522           if (our_md_test_algo (opt.extra_digest_algo) )
1523             log_error (_("selected digest algorithm is invalid\n"));
1524         }
1525     }
1526
1527   if (log_get_errorcount(0))
1528     gpgsm_exit(2);
1529
1530   /* Set the random seed file. */
1531   if (use_random_seed)
1532     {
1533       char *p = make_filename (opt.homedir, "random_seed", NULL);
1534       gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1535       xfree(p);
1536     }
1537
1538   if (!cmd && opt.fingerprint && !with_fpr)
1539     set_cmd (&cmd, aListKeys);
1540
1541   /* Add default keybox. */
1542   if (!nrings && default_keyring)
1543     {
1544       int created;
1545
1546       keydb_add_resource ("pubring.kbx", 0, 0, &created);
1547       if (created && !no_common_certs_import)
1548         {
1549           /* Import the standard certificates for a new default keybox. */
1550           char *filelist[2];
1551
1552           filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1553           filelist[1] = NULL;
1554           if (!access (filelist[0], F_OK))
1555             {
1556               log_info (_("importing common certificates `%s'\n"),
1557                         filelist[0]);
1558               gpgsm_import_files (&ctrl, 1, filelist, open_read);
1559             }
1560           xfree (filelist[0]);
1561         }
1562     }
1563   for (sl = nrings; sl; sl = sl->next)
1564     keydb_add_resource (sl->d, 0, 0, NULL);
1565   FREE_STRLIST(nrings);
1566
1567
1568   /* Prepare the audit log feature for certain commands.  */
1569   if (auditlog || htmlauditlog)
1570     {
1571       switch (cmd)
1572         {
1573         case aEncr:
1574         case aSign:
1575         case aDecrypt:
1576         case aVerify:
1577           audit_release (ctrl.audit);
1578           ctrl.audit = audit_new ();
1579           if (auditlog)
1580             auditfp = open_es_fwrite (auditlog);
1581           if (htmlauditlog)
1582             htmlauditfp = open_es_fwrite (htmlauditlog);
1583           break;
1584         default:
1585           break;
1586         }
1587     }
1588
1589
1590   if (!do_not_setup_keys)
1591     {
1592       for (sl = locusr; sl ; sl = sl->next)
1593         {
1594           int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1595           if (rc)
1596             {
1597               log_error (_("can't sign using `%s': %s\n"),
1598                          sl->d, gpg_strerror (rc));
1599               gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1600                              get_inv_recpsgnr_code (rc), sl->d, NULL);
1601               gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1602                              get_inv_recpsgnr_code (rc), sl->d, NULL);
1603             }
1604         }
1605
1606       /* Build the recipient list.  We first add the regular ones and then
1607          the encrypt-to ones because the underlying function will silently
1608          ignore duplicates and we can't allow to keep a duplicate which is
1609          flagged as encrypt-to as the actually encrypt function would then
1610          complain about no (regular) recipients. */
1611       for (sl = remusr; sl; sl = sl->next)
1612         if (!(sl->flags & 1))
1613           do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1614       if (!opt.no_encrypt_to)
1615         {
1616           for (sl = remusr; sl; sl = sl->next)
1617             if ((sl->flags & 1))
1618               do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1619         }
1620     }
1621
1622   if (log_get_errorcount(0))
1623     gpgsm_exit(1); /* Must stop for invalid recipients. */
1624
1625   /* Dispatch command.  */
1626   switch (cmd)
1627     {
1628     case aGPGConfList:
1629       { /* List options and default values in the GPG Conf format.  */
1630         char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1631
1632         printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1633                 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1634         xfree (config_filename_esc);
1635
1636         printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1637         printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1638         printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1639         printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1640         printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1641         printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1642         printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1643         printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1644                 DEFAULT_INCLUDE_CERTS);
1645         printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1646         printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1647         printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1648 #ifndef HAVE_W32_SYSTEM
1649         printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1650 #endif
1651         printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT);
1652         printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1653         printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1654         printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1655         printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1656
1657         /* The next one is an info only item and should match what
1658            proc_parameters actually implements.  */
1659         printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1660                 "RSA-2048");
1661       }
1662       break;
1663     case aGPGConfTest:
1664       /* This is merely a dummy command to test whether the
1665          configuration file is valid.  */
1666       break;
1667
1668     case aServer:
1669       if (debug_wait)
1670         {
1671           log_debug ("waiting for debugger - my pid is %u .....\n",
1672                      (unsigned int)getpid());
1673           gnupg_sleep (debug_wait);
1674           log_debug ("... okay\n");
1675          }
1676       gpgsm_server (recplist);
1677       break;
1678
1679     case aCallDirmngr:
1680       if (!argc)
1681         wrong_args ("--call-dirmngr <command> {args}");
1682       else
1683         if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1684           gpgsm_exit (1);
1685       break;
1686
1687     case aCallProtectTool:
1688       run_protect_tool (argc, argv);
1689       break;
1690
1691     case aEncr: /* Encrypt the given file. */
1692       {
1693         FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1694
1695         set_binary (stdin);
1696
1697         if (!argc) /* Source is stdin. */
1698           gpgsm_encrypt (&ctrl, recplist, 0, fp);
1699         else if (argc == 1)  /* Source is the given file. */
1700           gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1701         else
1702           wrong_args ("--encrypt [datafile]");
1703
1704         if (fp != stdout)
1705           fclose (fp);
1706       }
1707       break;
1708
1709     case aSign: /* Sign the given file. */
1710       {
1711         FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1712
1713         /* Fixme: We should also allow to concatenate multiple files for
1714            signing because that is what gpg does.*/
1715         set_binary (stdin);
1716         if (!argc) /* Create from stdin. */
1717           gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1718         else if (argc == 1) /* From file. */
1719           gpgsm_sign (&ctrl, signerlist,
1720                       open_read (*argv), detached_sig, fp);
1721         else
1722           wrong_args ("--sign [datafile]");
1723
1724         if (fp != stdout)
1725           fclose (fp);
1726       }
1727       break;
1728
1729     case aSignEncr: /* sign and encrypt the given file */
1730       log_error ("this command has not yet been implemented\n");
1731       break;
1732
1733     case aClearsign: /* make a clearsig */
1734       log_error ("this command has not yet been implemented\n");
1735       break;
1736
1737     case aVerify:
1738       {
1739         FILE *fp = NULL;
1740
1741         set_binary (stdin);
1742         if (argc == 2 && opt.outfile)
1743           log_info ("option --output ignored for a detached signature\n");
1744         else if (opt.outfile)
1745           fp = open_fwrite (opt.outfile);
1746
1747         if (!argc)
1748           gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1749         else if (argc == 1)
1750           gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1751         else if (argc == 2) /* detached signature (sig, detached) */
1752           gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1753         else
1754           wrong_args ("--verify [signature [detached_data]]");
1755
1756         if (fp && fp != stdout)
1757           fclose (fp);
1758       }
1759       break;
1760
1761     case aDecrypt:
1762       {
1763         FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1764
1765         set_binary (stdin);
1766         if (!argc)
1767           gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1768         else if (argc == 1)
1769           gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1770         else
1771           wrong_args ("--decrypt [filename]");
1772         if (fp != stdout)
1773           fclose (fp);
1774       }
1775       break;
1776
1777     case aDeleteKey:
1778       for (sl=NULL; argc; argc--, argv++)
1779         add_to_strlist (&sl, *argv);
1780       gpgsm_delete (&ctrl, sl);
1781       free_strlist(sl);
1782       break;
1783
1784     case aListChain:
1785     case aDumpChain:
1786        ctrl.with_chain = 1;
1787     case aListKeys:
1788     case aDumpKeys:
1789     case aListExternalKeys:
1790     case aDumpExternalKeys:
1791     case aListSecretKeys:
1792     case aDumpSecretKeys:
1793       {
1794         unsigned int mode;
1795         estream_t fp;
1796
1797         switch (cmd)
1798           {
1799           case aListChain:
1800           case aListKeys:         mode = (0   | 0 | (1<<6)); break;
1801           case aDumpChain:
1802           case aDumpKeys:         mode = (256 | 0 | (1<<6)); break;
1803           case aListExternalKeys: mode = (0   | 0 | (1<<7)); break;
1804           case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1805           case aListSecretKeys:   mode = (0   | 2 | (1<<6)); break;
1806           case aDumpSecretKeys:   mode = (256 | 2 | (1<<6)); break;
1807           default: BUG();
1808           }
1809
1810         fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1811         for (sl=NULL; argc; argc--, argv++)
1812           add_to_strlist (&sl, *argv);
1813         gpgsm_list_keys (&ctrl, sl, fp, mode);
1814         free_strlist(sl);
1815         es_fclose (fp);
1816       }
1817       break;
1818
1819
1820     case aKeygen: /* Generate a key; well kind of. */
1821       {
1822         estream_t fpin = NULL;
1823         FILE *fpout;
1824
1825         if (opt.batch)
1826           {
1827             if (!argc) /* Create from stdin. */
1828               fpin = open_es_fread ("-");
1829             else if (argc == 1) /* From file. */
1830               fpin = open_es_fread (*argv);
1831             else
1832               wrong_args ("--gen-key --batch [parmfile]");
1833           }
1834
1835         fpout = open_fwrite (opt.outfile?opt.outfile:"-");
1836
1837         if (fpin)
1838           gpgsm_genkey (&ctrl, fpin, fpout);
1839         else
1840           gpgsm_gencertreq_tty (&ctrl, fpout);
1841
1842         if (fpout != stdout)
1843           fclose (fpout);
1844       }
1845       break;
1846
1847
1848     case aImport:
1849       gpgsm_import_files (&ctrl, argc, argv, open_read);
1850       break;
1851
1852     case aExport:
1853       {
1854         FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1855
1856         for (sl=NULL; argc; argc--, argv++)
1857           add_to_strlist (&sl, *argv);
1858         gpgsm_export (&ctrl, sl, fp, NULL);
1859         free_strlist(sl);
1860         if (fp != stdout)
1861           fclose (fp);
1862       }
1863       break;
1864
1865     case aExportSecretKeyP12:
1866       {
1867         FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1868
1869         if (argc == 1)
1870           gpgsm_p12_export (&ctrl, *argv, fp);
1871         else
1872           wrong_args ("--export-secret-key-p12 KEY-ID");
1873         if (fp != stdout)
1874           fclose (fp);
1875       }
1876       break;
1877
1878     case aSendKeys:
1879     case aRecvKeys:
1880       log_error ("this command has not yet been implemented\n");
1881       break;
1882
1883
1884     case aLearnCard:
1885       if (argc)
1886         wrong_args ("--learn-card");
1887       else
1888         {
1889           int rc = gpgsm_agent_learn (&ctrl);
1890           if (rc)
1891             log_error ("error learning card: %s\n", gpg_strerror (rc));
1892         }
1893       break;
1894
1895     case aPasswd:
1896       if (argc != 1)
1897         wrong_args ("--passwd <key-Id>");
1898       else
1899         {
1900           int rc;
1901           ksba_cert_t cert = NULL;
1902           char *grip = NULL;
1903
1904           rc = gpgsm_find_cert (*argv, NULL, &cert);
1905           if (rc)
1906             ;
1907           else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1908             rc = gpg_error (GPG_ERR_BUG);
1909           else
1910             {
1911               char *desc = gpgsm_format_keydesc (cert);
1912               rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1913               xfree (desc);
1914             }
1915           if (rc)
1916             log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1917           xfree (grip);
1918           ksba_cert_release (cert);
1919         }
1920       break;
1921
1922     case aKeydbClearSomeCertFlags:
1923       for (sl=NULL; argc; argc--, argv++)
1924         add_to_strlist (&sl, *argv);
1925       keydb_clear_some_cert_flags (&ctrl, sl);
1926       free_strlist(sl);
1927       break;
1928
1929
1930     default:
1931         log_error (_("invalid command (there is no implicit command)\n"));
1932         break;
1933     }
1934
1935   /* Print the audit result if needed.  */
1936   if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
1937     {
1938       if (auditlog && auditfp)
1939         audit_print_result (ctrl.audit, auditfp, 0);
1940       if (htmlauditlog && htmlauditfp)
1941         audit_print_result (ctrl.audit, htmlauditfp, 1);
1942       audit_release (ctrl.audit);
1943       ctrl.audit = NULL;
1944       es_fclose (auditfp);
1945       es_fclose (htmlauditfp);
1946     }
1947
1948   /* cleanup */
1949   keyserver_list_free (opt.keyserver);
1950   opt.keyserver = NULL;
1951   gpgsm_release_certlist (recplist);
1952   gpgsm_release_certlist (signerlist);
1953   FREE_STRLIST (remusr);
1954   FREE_STRLIST (locusr);
1955   gpgsm_exit(0);
1956   return 8; /*NOTREACHED*/
1957 }
1958
1959 /* Note: This function is used by signal handlers!. */
1960 static void
1961 emergency_cleanup (void)
1962 {
1963   gcry_control (GCRYCTL_TERM_SECMEM );
1964 }
1965
1966
1967 void
1968 gpgsm_exit (int rc)
1969 {
1970   gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1971   if (opt.debug & DBG_MEMSTAT_VALUE)
1972     {
1973       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1974       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1975     }
1976   if (opt.debug)
1977     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1978   emergency_cleanup ();
1979   rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1980   exit (rc);
1981 }
1982
1983
1984 void
1985 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1986 {
1987   ctrl->include_certs = default_include_certs;
1988   ctrl->use_ocsp = opt.enable_ocsp;
1989   ctrl->validation_model = default_validation_model;
1990 }
1991
1992
1993 int
1994 gpgsm_parse_validation_model (const char *model)
1995 {
1996   if (!ascii_strcasecmp (model, "shell") )
1997     return 0;
1998   else if ( !ascii_strcasecmp (model, "chain") )
1999     return 1;
2000   else
2001     return -1;
2002 }
2003
2004
2005 /* Check whether the filename has the form "-&nnnn", where n is a
2006    non-zero number.  Returns this number or -1 if it is not the case.  */
2007 static int
2008 check_special_filename (const char *fname, int for_write)
2009 {
2010   if (allow_special_filenames
2011       && fname && *fname == '-' && fname[1] == '&' ) {
2012     int i;
2013
2014     fname += 2;
2015     for (i=0; isdigit (fname[i]); i++ )
2016       ;
2017     if ( !fname[i] )
2018       return translate_sys2libc_fd_int (atoi (fname), for_write);
2019   }
2020   return -1;
2021 }
2022
2023
2024
2025 /* Open the FILENAME for read and return the filedescriptor.  Stop
2026    with an error message in case of problems.  "-" denotes stdin and
2027    if special filenames are allowed the given fd is opened instead. */
2028 static int
2029 open_read (const char *filename)
2030 {
2031   int fd;
2032
2033   if (filename[0] == '-' && !filename[1])
2034     {
2035       set_binary (stdin);
2036       return 0; /* stdin */
2037     }
2038   fd = check_special_filename (filename, 0);
2039   if (fd != -1)
2040     return fd;
2041   fd = open (filename, O_RDONLY | O_BINARY);
2042   if (fd == -1)
2043     {
2044       log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2045       gpgsm_exit (2);
2046     }
2047   return fd;
2048 }
2049
2050 /* Same as open_read but return an estream_t.  */
2051 static estream_t
2052 open_es_fread (const char *filename)
2053 {
2054   int fd;
2055   estream_t fp;
2056
2057   if (filename[0] == '-' && !filename[1])
2058     fd = fileno (stdin);
2059   else
2060     fd = check_special_filename (filename, 0);
2061   if (fd != -1)
2062     {
2063       fp = es_fdopen_nc (fd, "rb");
2064       if (!fp)
2065         {
2066           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2067           gpgsm_exit (2);
2068         }
2069       return fp;
2070     }
2071   fp = es_fopen (filename, "rb");
2072   if (!fp)
2073     {
2074       log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2075       gpgsm_exit (2);
2076     }
2077   return fp;
2078 }
2079
2080
2081 /* Open FILENAME for fwrite and return the stream.  Stop with an error
2082    message in case of problems.  "-" denotes stdout and if special
2083    filenames are allowed the given fd is opened instead. Caller must
2084    close the returned stream unless it is stdout. */
2085 static FILE *
2086 open_fwrite (const char *filename)
2087 {
2088   int fd;
2089   FILE *fp;
2090
2091   if (filename[0] == '-' && !filename[1])
2092     {
2093       set_binary (stdout);
2094       return stdout;
2095     }
2096
2097   fd = check_special_filename (filename, 1);
2098   if (fd != -1)
2099     {
2100       fp = fdopen (dup (fd), "wb");
2101       if (!fp)
2102         {
2103           log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
2104           gpgsm_exit (2);
2105         }
2106       set_binary (fp);
2107       return fp;
2108     }
2109   fp = fopen (filename, "wb");
2110   if (!fp)
2111     {
2112       log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2113       gpgsm_exit (2);
2114     }
2115   return fp;
2116 }
2117
2118
2119 /* Open FILENAME for fwrite and return an extended stream.  Stop with
2120    an error message in case of problems.  "-" denotes stdout and if
2121    special filenames are allowed the given fd is opened instead.
2122    Caller must close the returned stream. */
2123 static estream_t
2124 open_es_fwrite (const char *filename)
2125 {
2126   int fd;
2127   estream_t fp;
2128
2129   if (filename[0] == '-' && !filename[1])
2130     {
2131       fflush (stdout);
2132       fp = es_fdopen_nc (fileno(stdout), "wb");
2133       return fp;
2134     }
2135
2136   fd = check_special_filename (filename, 1);
2137   if (fd != -1)
2138     {
2139       fp = es_fdopen_nc (fd, "wb");
2140       if (!fp)
2141         {
2142           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2143           gpgsm_exit (2);
2144         }
2145       return fp;
2146     }
2147   fp = es_fopen (filename, "wb");
2148   if (!fp)
2149     {
2150       log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2151       gpgsm_exit (2);
2152     }
2153   return fp;
2154 }
2155
2156
2157 static void
2158 run_protect_tool (int argc, char **argv)
2159 {
2160 #ifndef HAVE_W32_SYSTEM
2161   const char *pgm;
2162   char **av;
2163   int i;
2164
2165   if (!opt.protect_tool_program || !*opt.protect_tool_program)
2166     pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2167   else
2168     pgm = opt.protect_tool_program;
2169
2170   av = xcalloc (argc+2, sizeof *av);
2171   av[0] = strrchr (pgm, '/');
2172   if (!av[0])
2173     av[0] = xstrdup (pgm);
2174   for (i=1; argc; i++, argc--, argv++)
2175     av[i] = *argv;
2176   av[i] = NULL;
2177   execv (pgm, av);
2178   log_error ("error executing `%s': %s\n", pgm, strerror (errno));
2179 #endif /*HAVE_W32_SYSTEM*/
2180   gpgsm_exit (2);
2181 }