* gpg.texi (OpenPGP Options): Don't mention --no-sk-comment (doesn't
[gnupg.git] / sm / gpgsm.c
blob93e9076589988673959faef5ab90d72c628f6167
1 /* gpgsm.c - GnuPG for S/MIME
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007, 2008 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
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/>.
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>*/
31 #include "gpgsm.h"
32 #include <gcrypt.h>
33 #include <assuan.h> /* malloc hooks */
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"
42 #ifndef O_BINARY
43 #define O_BINARY 0
44 #endif
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,
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,
103 oEnableSpecialFilenames,
105 oAgentProgram,
106 oDisplay,
107 oTTYname,
108 oTTYtype,
109 oLCctype,
110 oLCmessages,
111 oXauthority,
113 oPreferSystemDirmngr,
114 oDirmngrProgram,
115 oDisableDirmngr,
116 oProtectToolProgram,
117 oFakedSystemTime,
120 oAssumeArmor,
121 oAssumeBase64,
122 oAssumeBinary,
124 oBase64,
125 oNoArmor,
126 oP12Charset,
128 oDisableCRLChecks,
129 oEnableCRLChecks,
130 oDisableTrustedCertCRLCheck,
131 oEnableTrustedCertCRLCheck,
132 oForceCRLRefresh,
134 oDisableOCSP,
135 oEnableOCSP,
137 oIncludeCerts,
138 oPolicyFile,
139 oDisablePolicyChecks,
140 oEnablePolicyChecks,
141 oAutoIssuerKeyRetrieve,
143 oWithFingerprint,
144 oWithMD5Fingerprint,
145 oAnswerYes,
146 oAnswerNo,
147 oKeyring,
148 oDefaultKey,
149 oDefRecipient,
150 oDefRecipientSelf,
151 oNoDefRecipient,
152 oStatusFD,
153 oCipherAlgo,
154 oDigestAlgo,
155 oExtraDigestAlgo,
156 oNoVerbose,
157 oNoSecmemWarn,
158 oNoDefKeyring,
159 oNoGreeting,
160 oNoTTY,
161 oNoOptions,
162 oNoBatch,
163 oHomedir,
164 oWithColons,
165 oWithKeyData,
166 oWithValidation,
167 oWithEphemeralKeys,
168 oSkipVerify,
169 oValidationModel,
170 oKeyServer,
171 oEncryptTo,
172 oNoEncryptTo,
173 oLoggerFD,
174 oDisableCipherAlgo,
175 oDisablePubkeyAlgo,
176 oIgnoreTimeConflict,
177 oNoRandomSeedFile,
178 oNoCommonCertsImport
182 static ARGPARSE_OPTS opts[] = {
184 ARGPARSE_group (300, N_("@Commands:\n ")),
186 ARGPARSE_c (aSign, "sign", N_("make a signature")),
187 ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),
188 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
189 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
190 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
191 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
192 ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
193 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
194 ARGPARSE_c (aListExternalKeys, "list-external-keys",
195 N_("list external keys")),
196 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
197 ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
198 ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
199 ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
200 ARGPARSE_c (aDeleteKey, "delete-keys",
201 N_("remove keys from the public keyring")),
202 ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a key server")),
203 ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a key server")),
204 ARGPARSE_c (aImport, "import", N_("import certificates")),
205 ARGPARSE_c (aExport, "export", N_("export certificates")),
206 ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
207 ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
208 ARGPARSE_c (aServer, "server", N_("run in server mode")),
209 ARGPARSE_c (aCallDirmngr, "call-dirmngr",
210 N_("pass a command to the dirmngr")),
211 ARGPARSE_c (aCallProtectTool, "call-protect-tool",
212 N_("invoke gpg-protect-tool")),
213 ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
214 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
215 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
217 ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
218 ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
219 ARGPARSE_c (aDumpChain, "dump-chain", "@"),
220 ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
221 ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
222 ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
224 ARGPARSE_group (301, N_("@\nOptions:\n ")),
226 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
227 ARGPARSE_s_n (oArmor, "armour", "@"),
228 ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
230 ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
232 ARGPARSE_s_n (oAssumeArmor, "assume-armor",
233 N_("assume input is in PEM format")),
234 ARGPARSE_s_n (oAssumeBase64, "assume-base64",
235 N_("assume input is in base-64 format")),
236 ARGPARSE_s_n (oAssumeBinary, "assume-binary",
237 N_("assume input is in binary format")),
239 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
241 ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr",
242 N_("use system's dirmngr if available")),
244 ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
245 N_("never consult a CRL")),
246 ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
247 ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
248 "disable-trusted-cert-crl-check", "@"),
249 ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
250 "enable-trusted-cert-crl-check", "@"),
252 ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
254 ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
255 ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
257 ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
259 ARGPARSE_s_i (oIncludeCerts, "include-certs",
260 N_("|N|number of certificates to include") ),
262 ARGPARSE_s_s (oPolicyFile, "policy-file",
263 N_("|FILE|take policy information from FILE")),
265 ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
266 N_("do not check certificate policies")),
267 ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
269 ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
270 N_("fetch missing issuer certificates")),
272 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
273 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
275 ARGPARSE_s_s (oUser, "local-user",
276 N_("|USER-ID|use USER-ID to sign or decrypt")),
278 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
279 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
280 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
281 ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
282 ARGPARSE_s_s (oLogFile, "log-file",
283 N_("|FILE|write a server mode log to FILE")),
284 ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
285 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
287 ARGPARSE_s_s (oAuditLog, "audit-log",
288 N_("|FILE|write an audit log to FILE")),
289 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
290 ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
291 ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
292 ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
294 ARGPARSE_s_s (oKeyring, "keyring",
295 N_("|FILE|add keyring to the list of keyrings")),
297 ARGPARSE_s_s (oDefaultKey, "default-key",
298 N_("|USER-ID|use USER-ID as default secret key")),
300 /* Not yet used: */
301 /* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
302 /* N_("|NAME|use NAME as default recipient")), */
303 /* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
304 /* N_("use the default key as default recipient")), */
305 /* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
307 ARGPARSE_s_s (oKeyServer, "keyserver",
308 N_("|SPEC|use this keyserver to lookup keys")),
309 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
311 ARGPARSE_p_u (oDebug, "debug", "@"),
312 ARGPARSE_s_s (oDebugLevel, "debug-level",
313 N_("|LEVEL|set the debugging level to LEVEL")),
314 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
315 ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
316 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
317 ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
318 ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
319 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
320 ARGPARSE_s_s (oFixedPassphrase, "fixed-passphrase", "@"),
322 ARGPARSE_s_i (oStatusFD, "status-fd",
323 N_("|FD|write status info to this FD")),
325 ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
326 N_("|NAME|use cipher algorithm NAME")),
327 ARGPARSE_s_s (oDigestAlgo, "digest-algo",
328 N_("|NAME|use message digest algorithm NAME")),
329 ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
332 ARGPARSE_group (302, N_(
333 "@\n(See the man page for a complete listing of all commands and options)\n"
336 ARGPARSE_group (303, N_("@\nExamples:\n\n"
337 " -se -r Bob [file] sign and encrypt for user Bob\n"
338 " --clearsign [file] make a clear text signature\n"
339 " --detach-sign [file] make a detached signature\n"
340 " --list-keys [names] show keys\n"
341 " --fingerprint [names] show fingerprints\n" )),
343 /* Hidden options. */
344 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
345 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
346 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
347 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
348 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
349 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
350 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
351 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
352 ARGPARSE_s_s (oHomedir, "homedir", "@"),
353 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
354 ARGPARSE_s_s (oDisplay, "display", "@"),
355 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
356 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
357 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
358 ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
359 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
360 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
361 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
362 ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
363 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
364 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
365 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
366 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
367 ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
368 ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
369 ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
370 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
371 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
372 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
373 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
374 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
375 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
376 ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
378 /* Command aliases. */
379 ARGPARSE_c (aListKeys, "list-key", "@"),
380 ARGPARSE_c (aListChain, "list-sig", "@"),
381 ARGPARSE_c (aListChain, "list-sigs", "@"),
382 ARGPARSE_c (aListChain, "check-sig", "@"),
383 ARGPARSE_c (aListChain, "check-sigs", "@"),
384 ARGPARSE_c (aDeleteKey, "delete-key", "@"),
386 ARGPARSE_end ()
392 /* Global variable to keep an error count. */
393 int gpgsm_errors_seen = 0;
395 /* It is possible that we are currentlu running under setuid permissions */
396 static int maybe_setuid = 1;
398 /* Helper to implement --debug-level and --debug*/
399 static const char *debug_level;
400 static unsigned int debug_value;
402 /* Option --enable-special-filenames */
403 static int allow_special_filenames;
405 /* Default value for include-certs. */
406 static int default_include_certs = 1; /* Only include the signer's cert. */
408 /* Whether the chain mode shall be used for validation. */
409 static int default_validation_model;
412 static char *build_list (const char *text,
413 const char *(*mapf)(int), int (*chkf)(int));
414 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
415 enum cmd_and_opt_values new_cmd );
417 static void emergency_cleanup (void);
418 static int check_special_filename (const char *fname, int for_write);
419 static int open_read (const char *filename);
420 static estream_t open_es_fread (const char *filename);
421 static FILE *open_fwrite (const char *filename);
422 static estream_t open_es_fwrite (const char *filename);
423 static void run_protect_tool (int argc, char **argv);
425 static int
426 our_pk_test_algo (int algo)
428 switch (algo)
430 case GCRY_PK_RSA:
431 case GCRY_PK_ECDSA:
432 return gcry_pk_test_algo (algo);
433 default:
434 return 1;
438 static int
439 our_cipher_test_algo (int algo)
441 switch (algo)
443 case GCRY_CIPHER_3DES:
444 case GCRY_CIPHER_AES128:
445 case GCRY_CIPHER_AES192:
446 case GCRY_CIPHER_AES256:
447 case GCRY_CIPHER_SERPENT128:
448 case GCRY_CIPHER_SERPENT192:
449 case GCRY_CIPHER_SERPENT256:
450 case GCRY_CIPHER_SEED:
451 case GCRY_CIPHER_CAMELLIA128:
452 case GCRY_CIPHER_CAMELLIA192:
453 case GCRY_CIPHER_CAMELLIA256:
454 return gcry_cipher_test_algo (algo);
455 default:
456 return 1;
461 static int
462 our_md_test_algo (int algo)
464 switch (algo)
466 case GCRY_MD_MD5:
467 case GCRY_MD_SHA1:
468 case GCRY_MD_RMD160:
469 case GCRY_MD_SHA224:
470 case GCRY_MD_SHA256:
471 case GCRY_MD_SHA384:
472 case GCRY_MD_SHA512:
473 case GCRY_MD_WHIRLPOOL:
474 return gcry_md_test_algo (algo);
475 default:
476 return 1;
481 static char *
482 make_libversion (const char *libname, const char *(*getfnc)(const char*))
484 const char *s;
485 char *result;
487 if (maybe_setuid)
489 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
490 maybe_setuid = 0;
492 s = getfnc (NULL);
493 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
494 strcpy (stpcpy (stpcpy (result, libname), " "), s);
495 return result;
499 static const char *
500 my_strusage( int level )
502 static char *digests, *pubkeys, *ciphers;
503 static char *ver_gcry, *ver_ksba;
504 const char *p;
506 switch (level)
508 case 11: p = "gpgsm (GnuPG)";
509 break;
510 case 13: p = VERSION; break;
511 case 17: p = PRINTABLE_OS_NAME; break;
512 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
514 case 1:
515 case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
516 break;
517 case 41:
518 p = _("Syntax: gpgsm [options] [files]\n"
519 "sign, check, encrypt or decrypt using the S/MIME protocol\n"
520 "default operation depends on the input data\n");
521 break;
523 case 20:
524 if (!ver_gcry)
525 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
526 p = ver_gcry;
527 break;
528 case 21:
529 if (!ver_ksba)
530 ver_ksba = make_libversion ("libksba", ksba_check_version);
531 p = ver_ksba;
532 break;
534 case 31: p = "\nHome: "; break;
535 case 32: p = opt.homedir; break;
536 case 33: p = _("\nSupported algorithms:\n"); break;
537 case 34:
538 if (!ciphers)
539 ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
540 our_cipher_test_algo );
541 p = ciphers;
542 break;
543 case 35:
544 if (!pubkeys)
545 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
546 our_pk_test_algo );
547 p = pubkeys;
548 break;
549 case 36:
550 if (!digests)
551 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
552 p = digests;
553 break;
555 default: p = NULL; break;
557 return p;
561 static char *
562 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
564 int i;
565 size_t n=strlen(text)+2;
566 char *list, *p;
568 if (maybe_setuid) {
569 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
572 for (i=1; i < 400; i++ )
573 if (!chkf(i))
574 n += strlen(mapf(i)) + 2;
575 list = xmalloc (21 + n);
576 *list = 0;
577 for (p=NULL, i=1; i < 400; i++)
579 if (!chkf(i))
581 if( !p )
582 p = stpcpy (list, text );
583 else
584 p = stpcpy (p, ", ");
585 p = stpcpy (p, mapf(i) );
588 if (p)
589 p = stpcpy(p, "\n" );
590 return list;
594 /* Set the file pointer into binary mode if required. */
595 static void
596 set_binary (FILE *fp)
598 #ifdef HAVE_DOSISH_SYSTEM
599 setmode (fileno (fp), O_BINARY);
600 #else
601 (void)fp;
602 #endif
607 static void
608 wrong_args (const char *text)
610 fputs (_("usage: gpgsm [options] "), stderr);
611 fputs (text, stderr);
612 putc ('\n', stderr);
613 gpgsm_exit (2);
617 static void
618 set_opt_session_env (const char *name, const char *value)
620 gpg_error_t err;
622 err = session_env_setenv (opt.session_env, name, value);
623 if (err)
624 log_fatal ("error setting session environment: %s\n",
625 gpg_strerror (err));
629 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
630 debug flags are propagated to the subsystems. With DEBUG_LEVEL
631 set, a specific set of debug flags is set; and individual debugging
632 flags will be added on top. */
633 static void
634 set_debug (void)
636 if (!debug_level)
638 else if (!strcmp (debug_level, "none"))
639 opt.debug = 0;
640 else if (!strcmp (debug_level, "basic"))
641 opt.debug = DBG_ASSUAN_VALUE;
642 else if (!strcmp (debug_level, "advanced"))
643 opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
644 else if (!strcmp (debug_level, "expert"))
645 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
646 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
647 else if (!strcmp (debug_level, "guru"))
648 opt.debug = ~0;
649 else
651 log_error (_("invalid debug-level `%s' given\n"), debug_level);
652 gpgsm_exit(2);
655 opt.debug |= debug_value;
657 if (opt.debug && !opt.verbose)
658 opt.verbose = 1;
659 if (opt.debug)
660 opt.quiet = 0;
662 if (opt.debug & DBG_MPI_VALUE)
663 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
664 if (opt.debug & DBG_CRYPTO_VALUE )
665 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
666 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
671 static void
672 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
674 enum cmd_and_opt_values cmd = *ret_cmd;
676 if (!cmd || cmd == new_cmd)
677 cmd = new_cmd;
678 else if ( cmd == aSign && new_cmd == aEncr )
679 cmd = aSignEncr;
680 else if ( cmd == aEncr && new_cmd == aSign )
681 cmd = aSignEncr;
682 else if ( (cmd == aSign && new_cmd == aClearsign)
683 || (cmd == aClearsign && new_cmd == aSign) )
684 cmd = aClearsign;
685 else
687 log_error(_("conflicting commands\n"));
688 gpgsm_exit(2);
691 *ret_cmd = cmd;
695 /* Helper to add recipients to a list. */
696 static void
697 do_add_recipient (ctrl_t ctrl, const char *name,
698 certlist_t *recplist, int is_encrypt_to, int recp_required)
700 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
701 if (rc)
703 if (recp_required)
705 log_error ("can't encrypt to `%s': %s\n", name, gpg_strerror (rc));
706 gpgsm_status2 (ctrl, STATUS_INV_RECP,
707 gpg_err_code (rc) == -1? "1":
708 gpg_err_code (rc) == GPG_ERR_NO_PUBKEY? "1":
709 gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME? "2":
710 gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE? "3":
711 gpg_err_code (rc) == GPG_ERR_CERT_REVOKED? "4":
712 gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED? "5":
713 gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN? "6":
714 gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD? "7":
715 gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH? "8":
716 "0",
717 name, NULL);
719 else
720 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
721 name, gpg_strerror (rc));
726 static void
727 parse_validation_model (const char *model)
729 int i = gpgsm_parse_validation_model (model);
730 if (i == -1)
731 log_error (_("unknown validation model `%s'\n"), model);
732 else
733 default_validation_model = i;
737 /* Release the list of SERVERS. As usual it is okay to call this
738 function with SERVERS passed as NULL. */
739 void
740 keyserver_list_free (struct keyserver_spec *servers)
742 while (servers)
744 struct keyserver_spec *tmp = servers->next;
745 xfree (servers->host);
746 xfree (servers->user);
747 if (servers->pass)
748 memset (servers->pass, 0, strlen (servers->pass));
749 xfree (servers->pass);
750 xfree (servers->base);
751 xfree (servers);
752 servers = tmp;
756 /* See also dirmngr ldapserver_parse_one(). */
757 struct keyserver_spec *
758 parse_keyserver_line (char *line,
759 const char *filename, unsigned int lineno)
761 char *p;
762 char *endp;
763 struct keyserver_spec *server;
764 int fieldno;
765 int fail = 0;
767 /* Parse the colon separated fields. */
768 server = xcalloc (1, sizeof *server);
769 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
771 endp = strchr (p, ':');
772 if (endp)
773 *endp++ = '\0';
774 trim_spaces (p);
775 switch (fieldno)
777 case 1:
778 if (*p)
779 server->host = xstrdup (p);
780 else
782 log_error (_("%s:%u: no hostname given\n"),
783 filename, lineno);
784 fail = 1;
786 break;
788 case 2:
789 if (*p)
790 server->port = atoi (p);
791 break;
793 case 3:
794 if (*p)
795 server->user = xstrdup (p);
796 break;
798 case 4:
799 if (*p && !server->user)
801 log_error (_("%s:%u: password given without user\n"),
802 filename, lineno);
803 fail = 1;
805 else if (*p)
806 server->pass = xstrdup (p);
807 break;
809 case 5:
810 if (*p)
811 server->base = xstrdup (p);
812 break;
814 default:
815 /* (We silently ignore extra fields.) */
816 break;
820 if (fail)
822 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
823 keyserver_list_free (server);
826 return server;
831 main ( int argc, char **argv)
833 ARGPARSE_ARGS pargs;
834 int orig_argc;
835 char **orig_argv;
836 const char *fname;
837 /* char *username;*/
838 int may_coredump;
839 strlist_t sl, remusr= NULL, locusr=NULL;
840 strlist_t nrings=NULL;
841 int detached_sig = 0;
842 FILE *configfp = NULL;
843 char *configname = NULL;
844 unsigned configlineno;
845 int parse_debug = 0;
846 int no_more_options = 0;
847 int default_config =1;
848 int default_keyring = 1;
849 char *logfile = NULL;
850 char *auditlog = NULL;
851 int greeting = 0;
852 int nogreeting = 0;
853 int debug_wait = 0;
854 int use_random_seed = 1;
855 int no_common_certs_import = 0;
856 int with_fpr = 0;
857 const char *forced_digest_algo = NULL;
858 const char *extra_digest_algo = NULL;
859 enum cmd_and_opt_values cmd = 0;
860 struct server_control_s ctrl;
861 certlist_t recplist = NULL;
862 certlist_t signerlist = NULL;
863 int do_not_setup_keys = 0;
864 int recp_required = 0;
865 estream_t auditfp = NULL;
867 /*mtrace();*/
869 gnupg_reopen_std ("gpgsm");
870 /* trap_unaligned ();*/
871 gnupg_rl_initialize ();
872 set_strusage (my_strusage);
873 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
874 /* We don't need any locking in libgcrypt unless we use any kind of
875 threading. */
876 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
878 /* Please note that we may running SUID(ROOT), so be very CAREFUL
879 when adding any stuff between here and the call to secmem_init()
880 somewhere after the option parsing */
881 log_set_prefix ("gpgsm", 1);
883 /* Make sure that our subsystems are ready. */
884 i18n_init();
885 init_common_subsystems ();
887 /* Check that the libraries are suitable. Do it here because the
888 option parse may need services of the library */
889 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
890 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
891 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
892 if (!ksba_check_version (NEED_KSBA_VERSION) )
893 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
894 NEED_KSBA_VERSION, ksba_check_version (NULL) );
897 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
899 may_coredump = disable_core_dumps ();
901 gnupg_init_signals (0, emergency_cleanup);
903 create_dotlock (NULL); /* register locking cleanup */
905 opt.session_env = session_env_new ();
906 if (!opt.session_env)
907 log_fatal ("error allocating session environment block: %s\n",
908 strerror (errno));
910 /* Note: If you change this default cipher algorithm , please
911 remember to update the Gpgconflist entry as well. */
912 opt.def_cipher_algoid = "3DES"; /*des-EDE3-CBC*/
914 opt.homedir = default_homedir ();
916 /* First check whether we have a config file on the commandline */
917 orig_argc = argc;
918 orig_argv = argv;
919 pargs.argc = &argc;
920 pargs.argv = &argv;
921 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
922 while (arg_parse( &pargs, opts))
924 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
925 parse_debug++;
926 else if (pargs.r_opt == oOptions)
927 { /* yes there is one, so we do not try the default one but
928 read the config file when it is encountered at the
929 commandline */
930 default_config = 0;
932 else if (pargs.r_opt == oNoOptions)
933 default_config = 0; /* --no-options */
934 else if (pargs.r_opt == oHomedir)
935 opt.homedir = pargs.r.ret_str;
936 else if (pargs.r_opt == aCallProtectTool)
937 break; /* This break makes sure that --version and --help are
938 passed to the protect-tool. */
942 /* Initialize the secure memory. */
943 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
944 maybe_setuid = 0;
947 Now we are now working under our real uid
950 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
952 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
953 assuan_set_assuan_log_stream (log_get_stream ());
954 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
955 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
957 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
959 /* Setup a default control structure for command line mode */
960 memset (&ctrl, 0, sizeof ctrl);
961 gpgsm_init_default_ctrl (&ctrl);
962 ctrl.no_server = 1;
963 ctrl.status_fd = -1; /* No status output. */
964 ctrl.autodetect_encoding = 1;
966 /* Set the default option file */
967 if (default_config )
968 configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
969 /* Set the default policy file */
970 opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
972 argc = orig_argc;
973 argv = orig_argv;
974 pargs.argc = &argc;
975 pargs.argv = &argv;
976 pargs.flags = 1; /* do not remove the args */
978 next_pass:
979 if (configname) {
980 configlineno = 0;
981 configfp = fopen (configname, "r");
982 if (!configfp)
984 if (default_config)
986 if (parse_debug)
987 log_info (_("NOTE: no default option file `%s'\n"), configname);
989 else
991 log_error (_("option file `%s': %s\n"), configname, strerror(errno));
992 gpgsm_exit(2);
994 xfree(configname);
995 configname = NULL;
997 if (parse_debug && configname)
998 log_info (_("reading options from `%s'\n"), configname);
999 default_config = 0;
1002 while (!no_more_options
1003 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1005 switch (pargs.r_opt)
1007 case aGPGConfList:
1008 case aGPGConfTest:
1009 set_cmd (&cmd, pargs.r_opt);
1010 do_not_setup_keys = 1;
1011 nogreeting = 1;
1012 break;
1014 case aServer:
1015 opt.batch = 1;
1016 set_cmd (&cmd, aServer);
1017 break;
1019 case aCallDirmngr:
1020 opt.batch = 1;
1021 set_cmd (&cmd, aCallDirmngr);
1022 do_not_setup_keys = 1;
1023 break;
1025 case aCallProtectTool:
1026 opt.batch = 1;
1027 set_cmd (&cmd, aCallProtectTool);
1028 no_more_options = 1; /* Stop parsing. */
1029 do_not_setup_keys = 1;
1030 break;
1032 case aDeleteKey:
1033 set_cmd (&cmd, aDeleteKey);
1034 /*greeting=1;*/
1035 do_not_setup_keys = 1;
1036 break;
1038 case aDetachedSign:
1039 detached_sig = 1;
1040 set_cmd (&cmd, aSign );
1041 break;
1043 case aKeygen:
1044 set_cmd (&cmd, aKeygen);
1045 greeting=1;
1046 do_not_setup_keys = 1;
1047 break;
1049 case aImport:
1050 case aSendKeys:
1051 case aRecvKeys:
1052 case aExport:
1053 case aExportSecretKeyP12:
1054 case aDumpKeys:
1055 case aDumpChain:
1056 case aDumpExternalKeys:
1057 case aDumpSecretKeys:
1058 case aListKeys:
1059 case aListExternalKeys:
1060 case aListSecretKeys:
1061 case aListChain:
1062 case aLearnCard:
1063 case aPasswd:
1064 case aKeydbClearSomeCertFlags:
1065 do_not_setup_keys = 1;
1066 set_cmd (&cmd, pargs.r_opt);
1067 break;
1069 case aEncr:
1070 recp_required = 1;
1071 set_cmd (&cmd, pargs.r_opt);
1072 break;
1074 case aSym:
1075 case aDecrypt:
1076 case aSign:
1077 case aClearsign:
1078 case aVerify:
1079 set_cmd (&cmd, pargs.r_opt);
1080 break;
1082 /* Output encoding selection. */
1083 case oArmor:
1084 ctrl.create_pem = 1;
1085 break;
1086 case oBase64:
1087 ctrl.create_pem = 0;
1088 ctrl.create_base64 = 1;
1089 break;
1090 case oNoArmor:
1091 ctrl.create_pem = 0;
1092 ctrl.create_base64 = 0;
1093 break;
1095 case oP12Charset:
1096 opt.p12_charset = pargs.r.ret_str;
1097 break;
1099 /* Input encoding selection. */
1100 case oAssumeArmor:
1101 ctrl.autodetect_encoding = 0;
1102 ctrl.is_pem = 1;
1103 ctrl.is_base64 = 0;
1104 break;
1105 case oAssumeBase64:
1106 ctrl.autodetect_encoding = 0;
1107 ctrl.is_pem = 0;
1108 ctrl.is_base64 = 1;
1109 break;
1110 case oAssumeBinary:
1111 ctrl.autodetect_encoding = 0;
1112 ctrl.is_pem = 0;
1113 ctrl.is_base64 = 0;
1114 break;
1116 case oDisableCRLChecks:
1117 opt.no_crl_check = 1;
1118 break;
1119 case oEnableCRLChecks:
1120 opt.no_crl_check = 0;
1121 break;
1122 case oDisableTrustedCertCRLCheck:
1123 opt.no_trusted_cert_crl_check = 1;
1124 break;
1125 case oEnableTrustedCertCRLCheck:
1126 opt.no_trusted_cert_crl_check = 0;
1127 break;
1128 case oForceCRLRefresh:
1129 opt.force_crl_refresh = 1;
1130 break;
1132 case oDisableOCSP:
1133 ctrl.use_ocsp = opt.enable_ocsp = 0;
1134 break;
1135 case oEnableOCSP:
1136 ctrl.use_ocsp = opt.enable_ocsp = 1;
1137 break;
1139 case oIncludeCerts:
1140 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1141 break;
1143 case oPolicyFile:
1144 xfree (opt.policy_file);
1145 if (*pargs.r.ret_str)
1146 opt.policy_file = xstrdup (pargs.r.ret_str);
1147 else
1148 opt.policy_file = NULL;
1149 break;
1151 case oDisablePolicyChecks:
1152 opt.no_policy_check = 1;
1153 break;
1154 case oEnablePolicyChecks:
1155 opt.no_policy_check = 0;
1156 break;
1158 case oAutoIssuerKeyRetrieve:
1159 opt.auto_issuer_key_retrieve = 1;
1160 break;
1162 case oOutput: opt.outfile = pargs.r.ret_str; break;
1165 case oQuiet: opt.quiet = 1; break;
1166 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1167 case oDryRun: opt.dry_run = 1; break;
1169 case oVerbose:
1170 opt.verbose++;
1171 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1172 break;
1173 case oNoVerbose:
1174 opt.verbose = 0;
1175 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1176 break;
1178 case oLogFile: logfile = pargs.r.ret_str; break;
1179 case oNoLogFile: logfile = NULL; break;
1181 case oAuditLog: auditlog = pargs.r.ret_str; break;
1183 case oBatch:
1184 opt.batch = 1;
1185 greeting = 0;
1186 break;
1187 case oNoBatch: opt.batch = 0; break;
1189 case oAnswerYes: opt.answer_yes = 1; break;
1190 case oAnswerNo: opt.answer_no = 1; break;
1192 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1194 case oDebug: debug_value |= pargs.r.ret_ulong; break;
1195 case oDebugAll: debug_value = ~0; break;
1196 case oDebugNone: debug_value = 0; break;
1197 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1198 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1199 case oDebugAllowCoreDump:
1200 may_coredump = enable_core_dumps ();
1201 break;
1202 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1203 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1204 case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1206 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1207 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1208 case oWithMD5Fingerprint:
1209 opt.with_md5_fingerprint=1; /*fall thru*/
1210 case oWithFingerprint:
1211 with_fpr=1; /*fall thru*/
1212 case aFingerprint:
1213 opt.fingerprint++;
1214 break;
1216 case oOptions:
1217 /* config files may not be nested (silently ignore them) */
1218 if (!configfp)
1220 xfree(configname);
1221 configname = xstrdup (pargs.r.ret_str);
1222 goto next_pass;
1224 break;
1225 case oNoOptions: break; /* no-options */
1226 case oHomedir: opt.homedir = pargs.r.ret_str; break;
1227 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1229 case oDisplay:
1230 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1231 break;
1232 case oTTYname:
1233 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1234 break;
1235 case oTTYtype:
1236 set_opt_session_env ("TERM", pargs.r.ret_str);
1237 break;
1238 case oXauthority:
1239 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1240 break;
1242 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1243 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1245 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1246 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1247 case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1248 case oProtectToolProgram:
1249 opt.protect_tool_program = pargs.r.ret_str;
1250 break;
1252 case oFakedSystemTime:
1254 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1255 if (faked_time == (time_t)(-1))
1256 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1257 gnupg_set_time (faked_time, 0);
1259 break;
1261 case oNoDefKeyring: default_keyring = 0; break;
1262 case oNoGreeting: nogreeting = 1; break;
1264 case oDefaultKey:
1265 if (*pargs.r.ret_str)
1267 xfree (opt.local_user);
1268 opt.local_user = xstrdup (pargs.r.ret_str);
1270 break;
1271 case oDefRecipient:
1272 if (*pargs.r.ret_str)
1273 opt.def_recipient = xstrdup (pargs.r.ret_str);
1274 break;
1275 case oDefRecipientSelf:
1276 xfree (opt.def_recipient);
1277 opt.def_recipient = NULL;
1278 opt.def_recipient_self = 1;
1279 break;
1280 case oNoDefRecipient:
1281 xfree (opt.def_recipient);
1282 opt.def_recipient = NULL;
1283 opt.def_recipient_self = 0;
1284 break;
1286 case oWithKeyData: opt.with_key_data=1; /* fall thru */
1287 case oWithColons: ctrl.with_colons = 1; break;
1288 case oWithValidation: ctrl.with_validation=1; break;
1289 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1291 case oSkipVerify: opt.skip_verify=1; break;
1293 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1294 case oEncryptTo: /* Store the recipient in the second list */
1295 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1296 sl->flags = 1;
1297 break;
1299 case oRecipient: /* store the recipient */
1300 add_to_strlist ( &remusr, pargs.r.ret_str);
1301 break;
1303 case oUser: /* Store the local users, the first one is the default */
1304 if (!opt.local_user)
1305 opt.local_user = xstrdup (pargs.r.ret_str);
1306 add_to_strlist (&locusr, pargs.r.ret_str);
1307 break;
1309 case oNoSecmemWarn:
1310 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1311 break;
1313 case oCipherAlgo:
1314 opt.def_cipher_algoid = pargs.r.ret_str;
1315 break;
1317 case oDisableCipherAlgo:
1319 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1320 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1322 break;
1323 case oDisablePubkeyAlgo:
1325 int algo = gcry_pk_map_name (pargs.r.ret_str);
1326 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1328 break;
1330 case oDigestAlgo:
1331 forced_digest_algo = pargs.r.ret_str;
1332 break;
1334 case oExtraDigestAlgo:
1335 extra_digest_algo = pargs.r.ret_str;
1336 break;
1338 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1339 case oNoRandomSeedFile: use_random_seed = 0; break;
1340 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1342 case oEnableSpecialFilenames: allow_special_filenames =1; break;
1344 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1346 case oKeyServer:
1348 struct keyserver_spec *keyserver;
1349 keyserver = parse_keyserver_line (pargs.r.ret_str,
1350 configname, configlineno);
1351 if (! keyserver)
1352 log_error (_("could not parse keyserver\n"));
1353 else
1355 /* FIXME: Keep last next pointer. */
1356 struct keyserver_spec **next_p = &opt.keyserver;
1357 while (*next_p)
1358 next_p = &(*next_p)->next;
1359 *next_p = keyserver;
1362 break;
1364 default:
1365 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1366 break;
1370 if (configfp)
1372 fclose (configfp);
1373 configfp = NULL;
1374 /* Keep a copy of the config filename. */
1375 opt.config_filename = configname;
1376 configname = NULL;
1377 goto next_pass;
1379 xfree (configname);
1380 configname = NULL;
1382 if (!opt.config_filename)
1383 opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1385 if (log_get_errorcount(0))
1386 gpgsm_exit(2);
1388 /* Now that we have the options parsed we need to update the default
1389 control structure. */
1390 gpgsm_init_default_ctrl (&ctrl);
1392 if (nogreeting)
1393 greeting = 0;
1395 if (greeting)
1397 fprintf(stderr, "%s %s; %s\n",
1398 strusage(11), strusage(13), strusage(14) );
1399 fprintf(stderr, "%s\n", strusage(15) );
1401 # ifdef IS_DEVELOPMENT_VERSION
1402 if (!opt.batch)
1404 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1405 log_info ("It is only intended for test purposes and should NOT be\n");
1406 log_info ("used in a production environment or with production keys!\n");
1408 # endif
1410 if (auditlog)
1411 log_info ("NOTE: The audit log feature (--audit-log) is "
1412 "WORK IN PRORESS and not ready for use!\n");
1415 if (may_coredump && !opt.quiet)
1416 log_info (_("WARNING: program may create a core file!\n"));
1418 /* if (opt.qualsig_approval && !opt.quiet) */
1419 /* log_info (_("This software has offically been approved to " */
1420 /* "create and verify\n" */
1421 /* "qualified signatures according to German law.\n")); */
1423 if (logfile && cmd == aServer)
1425 log_set_file (logfile);
1426 log_set_prefix (NULL, 1|2|4);
1429 if (gnupg_faked_time_p ())
1431 gnupg_isotime_t tbuf;
1433 log_info (_("WARNING: running with faked system time: "));
1434 gnupg_get_isotime (tbuf);
1435 dump_isotime (tbuf);
1436 log_printf ("\n");
1439 /*FIXME if (opt.batch) */
1440 /* tty_batchmode (1); */
1442 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1444 set_debug ();
1446 /* Although we alwasy use gpgsm_exit, we better install a regualr
1447 exit handler so that at least the secure memory gets wiped
1448 out. */
1449 if (atexit (emergency_cleanup))
1451 log_error ("atexit failed\n");
1452 gpgsm_exit (2);
1455 /* Must do this after dropping setuid, because the mapping functions
1456 may try to load an module and we may have disabled an algorithm.
1457 We remap the commonly used algorithms to the OIDs for
1458 convenience. We need to work with the OIDs because they are used
1459 to check whether the encryption mode is actually available. */
1460 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1461 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1462 else if (!strcmp (opt.def_cipher_algoid, "AES")
1463 || !strcmp (opt.def_cipher_algoid, "AES128"))
1464 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1465 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1466 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1467 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1468 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1469 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1470 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1471 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1472 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1473 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1474 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1475 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1476 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1477 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1478 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1479 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1480 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1481 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1482 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1484 if (cmd != aGPGConfList)
1486 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1487 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1488 log_error (_("selected cipher algorithm is invalid\n"));
1490 if (forced_digest_algo)
1492 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1493 if (our_md_test_algo(opt.forced_digest_algo) )
1494 log_error (_("selected digest algorithm is invalid\n"));
1496 if (extra_digest_algo)
1498 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1499 if (our_md_test_algo (opt.extra_digest_algo) )
1500 log_error (_("selected digest algorithm is invalid\n"));
1504 if (log_get_errorcount(0))
1505 gpgsm_exit(2);
1507 /* Set the random seed file. */
1508 if (use_random_seed)
1510 char *p = make_filename (opt.homedir, "random_seed", NULL);
1511 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1512 xfree(p);
1515 if (!cmd && opt.fingerprint && !with_fpr)
1516 set_cmd (&cmd, aListKeys);
1518 /* Add default keybox. */
1519 if (!nrings && default_keyring)
1521 int created;
1523 keydb_add_resource ("pubring.kbx", 0, 0, &created);
1524 if (created && !no_common_certs_import)
1526 /* Import the standard certificates for a new default keybox. */
1527 char *filelist[2];
1529 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1530 filelist[1] = NULL;
1531 if (!access (filelist[0], F_OK))
1533 log_info (_("importing common certificates `%s'\n"),
1534 filelist[0]);
1535 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1537 xfree (filelist[0]);
1540 for (sl = nrings; sl; sl = sl->next)
1541 keydb_add_resource (sl->d, 0, 0, NULL);
1542 FREE_STRLIST(nrings);
1545 /* Prepare the audit log feature for certain commands. */
1546 if (auditlog)
1548 switch (cmd)
1550 case aEncr:
1551 case aSign:
1552 case aDecrypt:
1553 case aVerify:
1554 audit_release (ctrl.audit);
1555 ctrl.audit = audit_new ();
1556 auditfp = open_es_fwrite (auditlog);
1557 break;
1558 default:
1559 break;
1564 if (!do_not_setup_keys)
1566 for (sl = locusr; sl ; sl = sl->next)
1568 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1569 if (rc)
1571 log_error (_("can't sign using `%s': %s\n"),
1572 sl->d, gpg_strerror (rc));
1573 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1574 gpg_err_code (rc) == -1? "1":
1575 gpg_err_code (rc) == GPG_ERR_NO_PUBKEY? "1":
1576 gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME? "2":
1577 gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE? "3":
1578 gpg_err_code (rc) == GPG_ERR_CERT_REVOKED? "4":
1579 gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED? "5":
1580 gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN? "6":
1581 gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD? "7":
1582 gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH? "8":
1583 gpg_err_code (rc) == GPG_ERR_NO_SECKEY? "9":
1584 "0",
1585 sl->d, NULL);
1589 /* Build the recipient list. We first add the regular ones and then
1590 the encrypt-to ones because the underlying function will silently
1591 ignore duplicates and we can't allow to keep a duplicate which is
1592 flagged as encrypt-to as the actually encrypt function would then
1593 complain about no (regular) recipients. */
1594 for (sl = remusr; sl; sl = sl->next)
1595 if (!(sl->flags & 1))
1596 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1597 if (!opt.no_encrypt_to)
1599 for (sl = remusr; sl; sl = sl->next)
1600 if ((sl->flags & 1))
1601 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1605 if (log_get_errorcount(0))
1606 gpgsm_exit(1); /* Must stop for invalid recipients. */
1608 fname = argc? *argv : NULL;
1610 /* Dispatch command. */
1611 switch (cmd)
1613 case aGPGConfList:
1614 { /* List options and default values in the GPG Conf format. */
1615 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1617 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1618 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1619 xfree (config_filename_esc);
1621 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1622 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1623 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1624 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1625 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1626 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1627 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1628 printf ("include-certs:%lu:1:\n", GC_OPT_FLAG_DEFAULT);
1629 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1630 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1631 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1632 #ifndef HAVE_W32_SYSTEM
1633 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1634 #endif
1635 printf ("cipher-algo:%lu:\"3DES:\n", GC_OPT_FLAG_DEFAULT);
1636 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1637 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1638 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1639 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1642 break;
1643 case aGPGConfTest:
1644 /* This is merely a dummy command to test whether the
1645 configuration file is valid. */
1646 break;
1648 case aServer:
1649 if (debug_wait)
1651 log_debug ("waiting for debugger - my pid is %u .....\n",
1652 (unsigned int)getpid());
1653 gnupg_sleep (debug_wait);
1654 log_debug ("... okay\n");
1656 gpgsm_server (recplist);
1657 break;
1659 case aCallDirmngr:
1660 if (!argc)
1661 wrong_args ("--call-dirmngr <command> {args}");
1662 else
1663 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1664 gpgsm_exit (1);
1665 break;
1667 case aCallProtectTool:
1668 run_protect_tool (argc, argv);
1669 break;
1671 case aEncr: /* Encrypt the given file. */
1673 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1675 set_binary (stdin);
1677 if (!argc) /* Source is stdin. */
1678 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1679 else if (argc == 1) /* Source is the given file. */
1680 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1681 else
1682 wrong_args ("--encrypt [datafile]");
1684 if (fp != stdout)
1685 fclose (fp);
1687 break;
1689 case aSign: /* Sign the given file. */
1691 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1693 /* Fixme: We should also allow to concatenate multiple files for
1694 signing because that is what gpg does.*/
1695 set_binary (stdin);
1696 if (!argc) /* Create from stdin. */
1697 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1698 else if (argc == 1) /* From file. */
1699 gpgsm_sign (&ctrl, signerlist,
1700 open_read (*argv), detached_sig, fp);
1701 else
1702 wrong_args ("--sign [datafile]");
1704 if (fp != stdout)
1705 fclose (fp);
1707 break;
1709 case aSignEncr: /* sign and encrypt the given file */
1710 log_error ("this command has not yet been implemented\n");
1711 break;
1713 case aClearsign: /* make a clearsig */
1714 log_error ("this command has not yet been implemented\n");
1715 break;
1717 case aVerify:
1719 FILE *fp = NULL;
1721 set_binary (stdin);
1722 if (argc == 2 && opt.outfile)
1723 log_info ("option --output ignored for a detached signature\n");
1724 else if (opt.outfile)
1725 fp = open_fwrite (opt.outfile);
1727 if (!argc)
1728 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1729 else if (argc == 1)
1730 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1731 else if (argc == 2) /* detached signature (sig, detached) */
1732 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1733 else
1734 wrong_args ("--verify [signature [detached_data]]");
1736 if (fp && fp != stdout)
1737 fclose (fp);
1739 break;
1741 case aDecrypt:
1743 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1745 set_binary (stdin);
1746 if (!argc)
1747 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1748 else if (argc == 1)
1749 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1750 else
1751 wrong_args ("--decrypt [filename]");
1752 if (fp != stdout)
1753 fclose (fp);
1755 break;
1757 case aDeleteKey:
1758 for (sl=NULL; argc; argc--, argv++)
1759 add_to_strlist (&sl, *argv);
1760 gpgsm_delete (&ctrl, sl);
1761 free_strlist(sl);
1762 break;
1764 case aListChain:
1765 case aDumpChain:
1766 ctrl.with_chain = 1;
1767 case aListKeys:
1768 case aDumpKeys:
1769 case aListExternalKeys:
1770 case aDumpExternalKeys:
1771 case aListSecretKeys:
1772 case aDumpSecretKeys:
1774 unsigned int mode;
1775 estream_t fp;
1777 switch (cmd)
1779 case aListChain:
1780 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1781 case aDumpChain:
1782 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1783 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1784 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1785 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1786 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1787 default: BUG();
1790 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1791 for (sl=NULL; argc; argc--, argv++)
1792 add_to_strlist (&sl, *argv);
1793 gpgsm_list_keys (&ctrl, sl, fp, mode);
1794 free_strlist(sl);
1795 es_fclose (fp);
1797 break;
1800 case aKeygen: /* Generate a key; well kind of. */
1802 estream_t fpin = NULL;
1803 FILE *fpout;
1805 if (opt.batch)
1807 if (!argc) /* Create from stdin. */
1808 fpin = open_es_fread ("-");
1809 else if (argc == 1) /* From file. */
1810 fpin = open_es_fread (*argv);
1811 else
1812 wrong_args ("--gen-key --batch [parmfile]");
1815 fpout = open_fwrite (opt.outfile?opt.outfile:"-");
1817 if (fpin)
1818 gpgsm_genkey (&ctrl, fpin, fpout);
1819 else
1820 gpgsm_gencertreq_tty (&ctrl, fpout);
1822 if (fpout != stdout)
1823 fclose (fpout);
1825 break;
1828 case aImport:
1829 gpgsm_import_files (&ctrl, argc, argv, open_read);
1830 break;
1832 case aExport:
1834 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1836 for (sl=NULL; argc; argc--, argv++)
1837 add_to_strlist (&sl, *argv);
1838 gpgsm_export (&ctrl, sl, fp, NULL);
1839 free_strlist(sl);
1840 if (fp != stdout)
1841 fclose (fp);
1843 break;
1845 case aExportSecretKeyP12:
1847 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1849 if (argc == 1)
1850 gpgsm_p12_export (&ctrl, *argv, fp);
1851 else
1852 wrong_args ("--export-secret-key-p12 KEY-ID");
1853 if (fp != stdout)
1854 fclose (fp);
1856 break;
1858 case aSendKeys:
1859 case aRecvKeys:
1860 log_error ("this command has not yet been implemented\n");
1861 break;
1864 case aLearnCard:
1865 if (argc)
1866 wrong_args ("--learn-card");
1867 else
1869 int rc = gpgsm_agent_learn (&ctrl);
1870 if (rc)
1871 log_error ("error learning card: %s\n", gpg_strerror (rc));
1873 break;
1875 case aPasswd:
1876 if (argc != 1)
1877 wrong_args ("--passwd <key-Id>");
1878 else
1880 int rc;
1881 ksba_cert_t cert = NULL;
1882 char *grip = NULL;
1884 rc = gpgsm_find_cert (*argv, NULL, &cert);
1885 if (rc)
1887 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1888 rc = gpg_error (GPG_ERR_BUG);
1889 else
1891 char *desc = gpgsm_format_keydesc (cert);
1892 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1893 xfree (desc);
1895 if (rc)
1896 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1897 xfree (grip);
1898 ksba_cert_release (cert);
1900 break;
1902 case aKeydbClearSomeCertFlags:
1903 for (sl=NULL; argc; argc--, argv++)
1904 add_to_strlist (&sl, *argv);
1905 keydb_clear_some_cert_flags (&ctrl, sl);
1906 free_strlist(sl);
1907 break;
1910 default:
1911 log_error (_("invalid command (there is no implicit command)\n"));
1912 break;
1915 /* Print the audit result if needed. */
1916 if (auditlog && auditfp)
1918 audit_print_result (ctrl.audit, auditfp, 0);
1919 audit_release (ctrl.audit);
1920 ctrl.audit = NULL;
1921 es_fclose (auditfp);
1924 /* cleanup */
1925 keyserver_list_free (opt.keyserver);
1926 opt.keyserver = NULL;
1927 gpgsm_release_certlist (recplist);
1928 gpgsm_release_certlist (signerlist);
1929 FREE_STRLIST (remusr);
1930 FREE_STRLIST (locusr);
1931 gpgsm_exit(0);
1932 return 8; /*NOTREACHED*/
1935 /* Note: This function is used by signal handlers!. */
1936 static void
1937 emergency_cleanup (void)
1939 gcry_control (GCRYCTL_TERM_SECMEM );
1943 void
1944 gpgsm_exit (int rc)
1946 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1947 if (opt.debug & DBG_MEMSTAT_VALUE)
1949 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1950 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1952 if (opt.debug)
1953 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1954 emergency_cleanup ();
1955 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1956 exit (rc);
1960 void
1961 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1963 ctrl->include_certs = default_include_certs;
1964 ctrl->use_ocsp = opt.enable_ocsp;
1965 ctrl->validation_model = default_validation_model;
1970 gpgsm_parse_validation_model (const char *model)
1972 if (!ascii_strcasecmp (model, "shell") )
1973 return 0;
1974 else if ( !ascii_strcasecmp (model, "chain") )
1975 return 1;
1976 else
1977 return -1;
1981 /* Check whether the filename has the form "-&nnnn", where n is a
1982 non-zero number. Returns this number or -1 if it is not the case. */
1983 static int
1984 check_special_filename (const char *fname, int for_write)
1986 if (allow_special_filenames
1987 && fname && *fname == '-' && fname[1] == '&' ) {
1988 int i;
1990 fname += 2;
1991 for (i=0; isdigit (fname[i]); i++ )
1993 if ( !fname[i] )
1994 return translate_sys2libc_fd_int (atoi (fname), for_write);
1996 return -1;
2001 /* Open the FILENAME for read and return the filedescriptor. Stop
2002 with an error message in case of problems. "-" denotes stdin and
2003 if special filenames are allowed the given fd is opened instead. */
2004 static int
2005 open_read (const char *filename)
2007 int fd;
2009 if (filename[0] == '-' && !filename[1])
2011 set_binary (stdin);
2012 return 0; /* stdin */
2014 fd = check_special_filename (filename, 0);
2015 if (fd != -1)
2016 return fd;
2017 fd = open (filename, O_RDONLY | O_BINARY);
2018 if (fd == -1)
2020 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2021 gpgsm_exit (2);
2023 return fd;
2026 /* Same as open_read but return an estream_t. */
2027 static estream_t
2028 open_es_fread (const char *filename)
2030 int fd;
2031 estream_t fp;
2033 if (filename[0] == '-' && !filename[1])
2034 fd = fileno (stdin);
2035 else
2036 fd = check_special_filename (filename, 0);
2037 if (fd != -1)
2039 fp = es_fdopen_nc (fd, "rb");
2040 if (!fp)
2042 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2043 gpgsm_exit (2);
2045 return fp;
2047 fp = es_fopen (filename, "rb");
2048 if (!fp)
2050 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2051 gpgsm_exit (2);
2053 return fp;
2057 /* Open FILENAME for fwrite and return the stream. Stop with an error
2058 message in case of problems. "-" denotes stdout and if special
2059 filenames are allowed the given fd is opened instead. Caller must
2060 close the returned stream unless it is stdout. */
2061 static FILE *
2062 open_fwrite (const char *filename)
2064 int fd;
2065 FILE *fp;
2067 if (filename[0] == '-' && !filename[1])
2069 set_binary (stdout);
2070 return stdout;
2073 fd = check_special_filename (filename, 1);
2074 if (fd != -1)
2076 fp = fdopen (dup (fd), "wb");
2077 if (!fp)
2079 log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
2080 gpgsm_exit (2);
2082 set_binary (fp);
2083 return fp;
2085 fp = fopen (filename, "wb");
2086 if (!fp)
2088 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2089 gpgsm_exit (2);
2091 return fp;
2095 /* Open FILENAME for fwrite and return an extended stream. Stop with
2096 an error message in case of problems. "-" denotes stdout and if
2097 special filenames are allowed the given fd is opened instead.
2098 Caller must close the returned stream. */
2099 static estream_t
2100 open_es_fwrite (const char *filename)
2102 int fd;
2103 estream_t fp;
2105 if (filename[0] == '-' && !filename[1])
2107 fflush (stdout);
2108 fp = es_fdopen_nc (fileno(stdout), "wb");
2109 return fp;
2112 fd = check_special_filename (filename, 1);
2113 if (fd != -1)
2115 fp = es_fdopen_nc (fd, "wb");
2116 if (!fp)
2118 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2119 gpgsm_exit (2);
2121 return fp;
2123 fp = es_fopen (filename, "wb");
2124 if (!fp)
2126 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2127 gpgsm_exit (2);
2129 return fp;
2133 static void
2134 run_protect_tool (int argc, char **argv)
2136 #ifndef HAVE_W32_SYSTEM
2137 const char *pgm;
2138 char **av;
2139 int i;
2141 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2142 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2143 else
2144 pgm = opt.protect_tool_program;
2146 av = xcalloc (argc+2, sizeof *av);
2147 av[0] = strrchr (pgm, '/');
2148 if (!av[0])
2149 av[0] = xstrdup (pgm);
2150 for (i=1; argc; i++, argc--, argv++)
2151 av[i] = *argv;
2152 av[i] = NULL;
2153 execv (pgm, av);
2154 log_error ("error executing `%s': %s\n", pgm, strerror (errno));
2155 #endif /*HAVE_W32_SYSTEM*/
2156 gpgsm_exit (2);