agent/
[gnupg.git] / sm / gpgsm.c
blobadfe6cdbf52a78b8a7189285c51c27ca73636083
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. We need an extra macro for
406 gpgconf-list because the variable will be changed by the command
407 line option.
409 It is often cumbersome to locate intermediate certificates, thus by
410 default we include all certificates in the chain. However we leave
411 out the root certificate because that would make it too easy for
412 the recipient to import that root certificate. A root certificate
413 should be installed only after due checks and thus it won't help to
414 send it along with each message. */
415 #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
416 static int default_include_certs = DEFAULT_INCLUDE_CERTS;
418 /* Whether the chain mode shall be used for validation. */
419 static int default_validation_model;
421 /* The default cipher algo. */
422 #define DEFAULT_CIPHER_ALGO "3DES" /*des-EDE3-CBC*/
425 static char *build_list (const char *text,
426 const char *(*mapf)(int), int (*chkf)(int));
427 static void set_cmd (enum cmd_and_opt_values *ret_cmd,
428 enum cmd_and_opt_values new_cmd );
430 static void emergency_cleanup (void);
431 static int check_special_filename (const char *fname, int for_write);
432 static int open_read (const char *filename);
433 static estream_t open_es_fread (const char *filename);
434 static FILE *open_fwrite (const char *filename);
435 static estream_t open_es_fwrite (const char *filename);
436 static void run_protect_tool (int argc, char **argv);
438 static int
439 our_pk_test_algo (int algo)
441 switch (algo)
443 case GCRY_PK_RSA:
444 case GCRY_PK_ECDSA:
445 return gcry_pk_test_algo (algo);
446 default:
447 return 1;
451 static int
452 our_cipher_test_algo (int algo)
454 switch (algo)
456 case GCRY_CIPHER_3DES:
457 case GCRY_CIPHER_AES128:
458 case GCRY_CIPHER_AES192:
459 case GCRY_CIPHER_AES256:
460 case GCRY_CIPHER_SERPENT128:
461 case GCRY_CIPHER_SERPENT192:
462 case GCRY_CIPHER_SERPENT256:
463 case GCRY_CIPHER_SEED:
464 case GCRY_CIPHER_CAMELLIA128:
465 case GCRY_CIPHER_CAMELLIA192:
466 case GCRY_CIPHER_CAMELLIA256:
467 return gcry_cipher_test_algo (algo);
468 default:
469 return 1;
474 static int
475 our_md_test_algo (int algo)
477 switch (algo)
479 case GCRY_MD_MD5:
480 case GCRY_MD_SHA1:
481 case GCRY_MD_RMD160:
482 case GCRY_MD_SHA224:
483 case GCRY_MD_SHA256:
484 case GCRY_MD_SHA384:
485 case GCRY_MD_SHA512:
486 case GCRY_MD_WHIRLPOOL:
487 return gcry_md_test_algo (algo);
488 default:
489 return 1;
494 static char *
495 make_libversion (const char *libname, const char *(*getfnc)(const char*))
497 const char *s;
498 char *result;
500 if (maybe_setuid)
502 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
503 maybe_setuid = 0;
505 s = getfnc (NULL);
506 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
507 strcpy (stpcpy (stpcpy (result, libname), " "), s);
508 return result;
512 static const char *
513 my_strusage( int level )
515 static char *digests, *pubkeys, *ciphers;
516 static char *ver_gcry, *ver_ksba;
517 const char *p;
519 switch (level)
521 case 11: p = "gpgsm (GnuPG)";
522 break;
523 case 13: p = VERSION; break;
524 case 17: p = PRINTABLE_OS_NAME; break;
525 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
527 case 1:
528 case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
529 break;
530 case 41:
531 p = _("Syntax: gpgsm [options] [files]\n"
532 "sign, check, encrypt or decrypt using the S/MIME protocol\n"
533 "default operation depends on the input data\n");
534 break;
536 case 20:
537 if (!ver_gcry)
538 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
539 p = ver_gcry;
540 break;
541 case 21:
542 if (!ver_ksba)
543 ver_ksba = make_libversion ("libksba", ksba_check_version);
544 p = ver_ksba;
545 break;
547 case 31: p = "\nHome: "; break;
548 case 32: p = opt.homedir; break;
549 case 33: p = _("\nSupported algorithms:\n"); break;
550 case 34:
551 if (!ciphers)
552 ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
553 our_cipher_test_algo );
554 p = ciphers;
555 break;
556 case 35:
557 if (!pubkeys)
558 pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
559 our_pk_test_algo );
560 p = pubkeys;
561 break;
562 case 36:
563 if (!digests)
564 digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
565 p = digests;
566 break;
568 default: p = NULL; break;
570 return p;
574 static char *
575 build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
577 int i;
578 size_t n=strlen(text)+2;
579 char *list, *p;
581 if (maybe_setuid) {
582 gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
585 for (i=1; i < 400; i++ )
586 if (!chkf(i))
587 n += strlen(mapf(i)) + 2;
588 list = xmalloc (21 + n);
589 *list = 0;
590 for (p=NULL, i=1; i < 400; i++)
592 if (!chkf(i))
594 if( !p )
595 p = stpcpy (list, text );
596 else
597 p = stpcpy (p, ", ");
598 p = stpcpy (p, mapf(i) );
601 if (p)
602 p = stpcpy(p, "\n" );
603 return list;
607 /* Set the file pointer into binary mode if required. */
608 static void
609 set_binary (FILE *fp)
611 #ifdef HAVE_DOSISH_SYSTEM
612 setmode (fileno (fp), O_BINARY);
613 #else
614 (void)fp;
615 #endif
620 static void
621 wrong_args (const char *text)
623 fputs (_("usage: gpgsm [options] "), stderr);
624 fputs (text, stderr);
625 putc ('\n', stderr);
626 gpgsm_exit (2);
630 static void
631 set_opt_session_env (const char *name, const char *value)
633 gpg_error_t err;
635 err = session_env_setenv (opt.session_env, name, value);
636 if (err)
637 log_fatal ("error setting session environment: %s\n",
638 gpg_strerror (err));
642 /* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
643 debug flags are propagated to the subsystems. With DEBUG_LEVEL
644 set, a specific set of debug flags is set; and individual debugging
645 flags will be added on top. */
646 static void
647 set_debug (void)
649 if (!debug_level)
651 else if (!strcmp (debug_level, "none"))
652 opt.debug = 0;
653 else if (!strcmp (debug_level, "basic"))
654 opt.debug = DBG_ASSUAN_VALUE;
655 else if (!strcmp (debug_level, "advanced"))
656 opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
657 else if (!strcmp (debug_level, "expert"))
658 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
659 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
660 else if (!strcmp (debug_level, "guru"))
661 opt.debug = ~0;
662 else
664 log_error (_("invalid debug-level `%s' given\n"), debug_level);
665 gpgsm_exit(2);
668 opt.debug |= debug_value;
670 if (opt.debug && !opt.verbose)
671 opt.verbose = 1;
672 if (opt.debug)
673 opt.quiet = 0;
675 if (opt.debug & DBG_MPI_VALUE)
676 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
677 if (opt.debug & DBG_CRYPTO_VALUE )
678 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
679 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
684 static void
685 set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
687 enum cmd_and_opt_values cmd = *ret_cmd;
689 if (!cmd || cmd == new_cmd)
690 cmd = new_cmd;
691 else if ( cmd == aSign && new_cmd == aEncr )
692 cmd = aSignEncr;
693 else if ( cmd == aEncr && new_cmd == aSign )
694 cmd = aSignEncr;
695 else if ( (cmd == aSign && new_cmd == aClearsign)
696 || (cmd == aClearsign && new_cmd == aSign) )
697 cmd = aClearsign;
698 else
700 log_error(_("conflicting commands\n"));
701 gpgsm_exit(2);
704 *ret_cmd = cmd;
708 /* Helper to add recipients to a list. */
709 static void
710 do_add_recipient (ctrl_t ctrl, const char *name,
711 certlist_t *recplist, int is_encrypt_to, int recp_required)
713 int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
714 if (rc)
716 if (recp_required)
718 log_error ("can't encrypt to `%s': %s\n", name, gpg_strerror (rc));
719 gpgsm_status2 (ctrl, STATUS_INV_RECP,
720 get_inv_recpsgnr_code (rc), name, NULL);
722 else
723 log_info (_("NOTE: won't be able to encrypt to `%s': %s\n"),
724 name, gpg_strerror (rc));
729 static void
730 parse_validation_model (const char *model)
732 int i = gpgsm_parse_validation_model (model);
733 if (i == -1)
734 log_error (_("unknown validation model `%s'\n"), model);
735 else
736 default_validation_model = i;
740 /* Release the list of SERVERS. As usual it is okay to call this
741 function with SERVERS passed as NULL. */
742 void
743 keyserver_list_free (struct keyserver_spec *servers)
745 while (servers)
747 struct keyserver_spec *tmp = servers->next;
748 xfree (servers->host);
749 xfree (servers->user);
750 if (servers->pass)
751 memset (servers->pass, 0, strlen (servers->pass));
752 xfree (servers->pass);
753 xfree (servers->base);
754 xfree (servers);
755 servers = tmp;
759 /* See also dirmngr ldapserver_parse_one(). */
760 struct keyserver_spec *
761 parse_keyserver_line (char *line,
762 const char *filename, unsigned int lineno)
764 char *p;
765 char *endp;
766 struct keyserver_spec *server;
767 int fieldno;
768 int fail = 0;
770 /* Parse the colon separated fields. */
771 server = xcalloc (1, sizeof *server);
772 for (fieldno = 1, p = line; p; p = endp, fieldno++ )
774 endp = strchr (p, ':');
775 if (endp)
776 *endp++ = '\0';
777 trim_spaces (p);
778 switch (fieldno)
780 case 1:
781 if (*p)
782 server->host = xstrdup (p);
783 else
785 log_error (_("%s:%u: no hostname given\n"),
786 filename, lineno);
787 fail = 1;
789 break;
791 case 2:
792 if (*p)
793 server->port = atoi (p);
794 break;
796 case 3:
797 if (*p)
798 server->user = xstrdup (p);
799 break;
801 case 4:
802 if (*p && !server->user)
804 log_error (_("%s:%u: password given without user\n"),
805 filename, lineno);
806 fail = 1;
808 else if (*p)
809 server->pass = xstrdup (p);
810 break;
812 case 5:
813 if (*p)
814 server->base = xstrdup (p);
815 break;
817 default:
818 /* (We silently ignore extra fields.) */
819 break;
823 if (fail)
825 log_info (_("%s:%u: skipping this line\n"), filename, lineno);
826 keyserver_list_free (server);
829 return server;
834 main ( int argc, char **argv)
836 ARGPARSE_ARGS pargs;
837 int orig_argc;
838 char **orig_argv;
839 const char *fname;
840 /* char *username;*/
841 int may_coredump;
842 strlist_t sl, remusr= NULL, locusr=NULL;
843 strlist_t nrings=NULL;
844 int detached_sig = 0;
845 FILE *configfp = NULL;
846 char *configname = NULL;
847 unsigned configlineno;
848 int parse_debug = 0;
849 int no_more_options = 0;
850 int default_config =1;
851 int default_keyring = 1;
852 char *logfile = NULL;
853 char *auditlog = NULL;
854 int greeting = 0;
855 int nogreeting = 0;
856 int debug_wait = 0;
857 int use_random_seed = 1;
858 int no_common_certs_import = 0;
859 int with_fpr = 0;
860 const char *forced_digest_algo = NULL;
861 const char *extra_digest_algo = NULL;
862 enum cmd_and_opt_values cmd = 0;
863 struct server_control_s ctrl;
864 certlist_t recplist = NULL;
865 certlist_t signerlist = NULL;
866 int do_not_setup_keys = 0;
867 int recp_required = 0;
868 estream_t auditfp = NULL;
869 struct assuan_malloc_hooks malloc_hooks;
871 /*mtrace();*/
873 gnupg_reopen_std ("gpgsm");
874 /* trap_unaligned ();*/
875 gnupg_rl_initialize ();
876 set_strusage (my_strusage);
877 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
879 /* Please note that we may running SUID(ROOT), so be very CAREFUL
880 when adding any stuff between here and the call to secmem_init()
881 somewhere after the option parsing */
882 log_set_prefix ("gpgsm", 1);
884 /* Make sure that our subsystems are ready. */
885 i18n_init();
886 init_common_subsystems ();
888 /* Check that the libraries are suitable. Do it here because the
889 option parse may need services of the library */
890 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
891 log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
892 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
893 if (!ksba_check_version (NEED_KSBA_VERSION) )
894 log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
895 NEED_KSBA_VERSION, ksba_check_version (NULL) );
898 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
900 may_coredump = disable_core_dumps ();
902 gnupg_init_signals (0, emergency_cleanup);
904 create_dotlock (NULL); /* register locking cleanup */
906 opt.session_env = session_env_new ();
907 if (!opt.session_env)
908 log_fatal ("error allocating session environment block: %s\n",
909 strerror (errno));
911 /* Note: If you change this default cipher algorithm , please
912 remember to update the Gpgconflist entry as well. */
913 opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
915 opt.homedir = default_homedir ();
917 /* First check whether we have a config file on the commandline */
918 orig_argc = argc;
919 orig_argv = argv;
920 pargs.argc = &argc;
921 pargs.argv = &argv;
922 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
923 while (arg_parse( &pargs, opts))
925 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
926 parse_debug++;
927 else if (pargs.r_opt == oOptions)
928 { /* yes there is one, so we do not try the default one but
929 read the config file when it is encountered at the
930 commandline */
931 default_config = 0;
933 else if (pargs.r_opt == oNoOptions)
934 default_config = 0; /* --no-options */
935 else if (pargs.r_opt == oHomedir)
936 opt.homedir = pargs.r.ret_str;
937 else if (pargs.r_opt == aCallProtectTool)
938 break; /* This break makes sure that --version and --help are
939 passed to the protect-tool. */
943 /* Initialize the secure memory. */
944 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
945 maybe_setuid = 0;
948 Now we are now working under our real uid
951 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
953 malloc_hooks.malloc = gcry_malloc;
954 malloc_hooks.realloc = gcry_realloc;
955 malloc_hooks.free = gcry_free;
956 assuan_set_malloc_hooks (&malloc_hooks);
957 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
958 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
960 keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
962 /* Setup a default control structure for command line mode */
963 memset (&ctrl, 0, sizeof ctrl);
964 gpgsm_init_default_ctrl (&ctrl);
965 ctrl.no_server = 1;
966 ctrl.status_fd = -1; /* No status output. */
967 ctrl.autodetect_encoding = 1;
969 /* Set the default option file */
970 if (default_config )
971 configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
972 /* Set the default policy file */
973 opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
975 argc = orig_argc;
976 argv = orig_argv;
977 pargs.argc = &argc;
978 pargs.argv = &argv;
979 pargs.flags = 1; /* do not remove the args */
981 next_pass:
982 if (configname) {
983 configlineno = 0;
984 configfp = fopen (configname, "r");
985 if (!configfp)
987 if (default_config)
989 if (parse_debug)
990 log_info (_("NOTE: no default option file `%s'\n"), configname);
992 else
994 log_error (_("option file `%s': %s\n"), configname, strerror(errno));
995 gpgsm_exit(2);
997 xfree(configname);
998 configname = NULL;
1000 if (parse_debug && configname)
1001 log_info (_("reading options from `%s'\n"), configname);
1002 default_config = 0;
1005 while (!no_more_options
1006 && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
1008 switch (pargs.r_opt)
1010 case aGPGConfList:
1011 case aGPGConfTest:
1012 set_cmd (&cmd, pargs.r_opt);
1013 do_not_setup_keys = 1;
1014 nogreeting = 1;
1015 break;
1017 case aServer:
1018 opt.batch = 1;
1019 set_cmd (&cmd, aServer);
1020 break;
1022 case aCallDirmngr:
1023 opt.batch = 1;
1024 set_cmd (&cmd, aCallDirmngr);
1025 do_not_setup_keys = 1;
1026 break;
1028 case aCallProtectTool:
1029 opt.batch = 1;
1030 set_cmd (&cmd, aCallProtectTool);
1031 no_more_options = 1; /* Stop parsing. */
1032 do_not_setup_keys = 1;
1033 break;
1035 case aDeleteKey:
1036 set_cmd (&cmd, aDeleteKey);
1037 /*greeting=1;*/
1038 do_not_setup_keys = 1;
1039 break;
1041 case aDetachedSign:
1042 detached_sig = 1;
1043 set_cmd (&cmd, aSign );
1044 break;
1046 case aKeygen:
1047 set_cmd (&cmd, aKeygen);
1048 greeting=1;
1049 do_not_setup_keys = 1;
1050 break;
1052 case aImport:
1053 case aSendKeys:
1054 case aRecvKeys:
1055 case aExport:
1056 case aExportSecretKeyP12:
1057 case aDumpKeys:
1058 case aDumpChain:
1059 case aDumpExternalKeys:
1060 case aDumpSecretKeys:
1061 case aListKeys:
1062 case aListExternalKeys:
1063 case aListSecretKeys:
1064 case aListChain:
1065 case aLearnCard:
1066 case aPasswd:
1067 case aKeydbClearSomeCertFlags:
1068 do_not_setup_keys = 1;
1069 set_cmd (&cmd, pargs.r_opt);
1070 break;
1072 case aEncr:
1073 recp_required = 1;
1074 set_cmd (&cmd, pargs.r_opt);
1075 break;
1077 case aSym:
1078 case aDecrypt:
1079 case aSign:
1080 case aClearsign:
1081 case aVerify:
1082 set_cmd (&cmd, pargs.r_opt);
1083 break;
1085 /* Output encoding selection. */
1086 case oArmor:
1087 ctrl.create_pem = 1;
1088 break;
1089 case oBase64:
1090 ctrl.create_pem = 0;
1091 ctrl.create_base64 = 1;
1092 break;
1093 case oNoArmor:
1094 ctrl.create_pem = 0;
1095 ctrl.create_base64 = 0;
1096 break;
1098 case oP12Charset:
1099 opt.p12_charset = pargs.r.ret_str;
1100 break;
1102 /* Input encoding selection. */
1103 case oAssumeArmor:
1104 ctrl.autodetect_encoding = 0;
1105 ctrl.is_pem = 1;
1106 ctrl.is_base64 = 0;
1107 break;
1108 case oAssumeBase64:
1109 ctrl.autodetect_encoding = 0;
1110 ctrl.is_pem = 0;
1111 ctrl.is_base64 = 1;
1112 break;
1113 case oAssumeBinary:
1114 ctrl.autodetect_encoding = 0;
1115 ctrl.is_pem = 0;
1116 ctrl.is_base64 = 0;
1117 break;
1119 case oDisableCRLChecks:
1120 opt.no_crl_check = 1;
1121 break;
1122 case oEnableCRLChecks:
1123 opt.no_crl_check = 0;
1124 break;
1125 case oDisableTrustedCertCRLCheck:
1126 opt.no_trusted_cert_crl_check = 1;
1127 break;
1128 case oEnableTrustedCertCRLCheck:
1129 opt.no_trusted_cert_crl_check = 0;
1130 break;
1131 case oForceCRLRefresh:
1132 opt.force_crl_refresh = 1;
1133 break;
1135 case oDisableOCSP:
1136 ctrl.use_ocsp = opt.enable_ocsp = 0;
1137 break;
1138 case oEnableOCSP:
1139 ctrl.use_ocsp = opt.enable_ocsp = 1;
1140 break;
1142 case oIncludeCerts:
1143 ctrl.include_certs = default_include_certs = pargs.r.ret_int;
1144 break;
1146 case oPolicyFile:
1147 xfree (opt.policy_file);
1148 if (*pargs.r.ret_str)
1149 opt.policy_file = xstrdup (pargs.r.ret_str);
1150 else
1151 opt.policy_file = NULL;
1152 break;
1154 case oDisablePolicyChecks:
1155 opt.no_policy_check = 1;
1156 break;
1157 case oEnablePolicyChecks:
1158 opt.no_policy_check = 0;
1159 break;
1161 case oAutoIssuerKeyRetrieve:
1162 opt.auto_issuer_key_retrieve = 1;
1163 break;
1165 case oOutput: opt.outfile = pargs.r.ret_str; break;
1168 case oQuiet: opt.quiet = 1; break;
1169 case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
1170 case oDryRun: opt.dry_run = 1; break;
1172 case oVerbose:
1173 opt.verbose++;
1174 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1175 break;
1176 case oNoVerbose:
1177 opt.verbose = 0;
1178 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1179 break;
1181 case oLogFile: logfile = pargs.r.ret_str; break;
1182 case oNoLogFile: logfile = NULL; break;
1184 case oAuditLog: auditlog = pargs.r.ret_str; break;
1186 case oBatch:
1187 opt.batch = 1;
1188 greeting = 0;
1189 break;
1190 case oNoBatch: opt.batch = 0; break;
1192 case oAnswerYes: opt.answer_yes = 1; break;
1193 case oAnswerNo: opt.answer_no = 1; break;
1195 case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
1197 case oDebug: debug_value |= pargs.r.ret_ulong; break;
1198 case oDebugAll: debug_value = ~0; break;
1199 case oDebugNone: debug_value = 0; break;
1200 case oDebugLevel: debug_level = pargs.r.ret_str; break;
1201 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1202 case oDebugAllowCoreDump:
1203 may_coredump = enable_core_dumps ();
1204 break;
1205 case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
1206 case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
1207 case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
1209 case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
1210 case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
1211 case oWithMD5Fingerprint:
1212 opt.with_md5_fingerprint=1; /*fall thru*/
1213 case oWithFingerprint:
1214 with_fpr=1; /*fall thru*/
1215 case aFingerprint:
1216 opt.fingerprint++;
1217 break;
1219 case oOptions:
1220 /* config files may not be nested (silently ignore them) */
1221 if (!configfp)
1223 xfree(configname);
1224 configname = xstrdup (pargs.r.ret_str);
1225 goto next_pass;
1227 break;
1228 case oNoOptions: break; /* no-options */
1229 case oHomedir: opt.homedir = pargs.r.ret_str; break;
1230 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
1232 case oDisplay:
1233 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
1234 break;
1235 case oTTYname:
1236 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
1237 break;
1238 case oTTYtype:
1239 set_opt_session_env ("TERM", pargs.r.ret_str);
1240 break;
1241 case oXauthority:
1242 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
1243 break;
1245 case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
1246 case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
1248 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
1249 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
1250 case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
1251 case oProtectToolProgram:
1252 opt.protect_tool_program = pargs.r.ret_str;
1253 break;
1255 case oFakedSystemTime:
1257 time_t faked_time = isotime2epoch (pargs.r.ret_str);
1258 if (faked_time == (time_t)(-1))
1259 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
1260 gnupg_set_time (faked_time, 0);
1262 break;
1264 case oNoDefKeyring: default_keyring = 0; break;
1265 case oNoGreeting: nogreeting = 1; break;
1267 case oDefaultKey:
1268 if (*pargs.r.ret_str)
1270 xfree (opt.local_user);
1271 opt.local_user = xstrdup (pargs.r.ret_str);
1273 break;
1274 case oDefRecipient:
1275 if (*pargs.r.ret_str)
1276 opt.def_recipient = xstrdup (pargs.r.ret_str);
1277 break;
1278 case oDefRecipientSelf:
1279 xfree (opt.def_recipient);
1280 opt.def_recipient = NULL;
1281 opt.def_recipient_self = 1;
1282 break;
1283 case oNoDefRecipient:
1284 xfree (opt.def_recipient);
1285 opt.def_recipient = NULL;
1286 opt.def_recipient_self = 0;
1287 break;
1289 case oWithKeyData: opt.with_key_data=1; /* fall thru */
1290 case oWithColons: ctrl.with_colons = 1; break;
1291 case oWithValidation: ctrl.with_validation=1; break;
1292 case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
1294 case oSkipVerify: opt.skip_verify=1; break;
1296 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
1297 case oEncryptTo: /* Store the recipient in the second list */
1298 sl = add_to_strlist (&remusr, pargs.r.ret_str);
1299 sl->flags = 1;
1300 break;
1302 case oRecipient: /* store the recipient */
1303 add_to_strlist ( &remusr, pargs.r.ret_str);
1304 break;
1306 case oUser: /* Store the local users, the first one is the default */
1307 if (!opt.local_user)
1308 opt.local_user = xstrdup (pargs.r.ret_str);
1309 add_to_strlist (&locusr, pargs.r.ret_str);
1310 break;
1312 case oNoSecmemWarn:
1313 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
1314 break;
1316 case oCipherAlgo:
1317 opt.def_cipher_algoid = pargs.r.ret_str;
1318 break;
1320 case oDisableCipherAlgo:
1322 int algo = gcry_cipher_map_name (pargs.r.ret_str);
1323 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
1325 break;
1326 case oDisablePubkeyAlgo:
1328 int algo = gcry_pk_map_name (pargs.r.ret_str);
1329 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
1331 break;
1333 case oDigestAlgo:
1334 forced_digest_algo = pargs.r.ret_str;
1335 break;
1337 case oExtraDigestAlgo:
1338 extra_digest_algo = pargs.r.ret_str;
1339 break;
1341 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
1342 case oNoRandomSeedFile: use_random_seed = 0; break;
1343 case oNoCommonCertsImport: no_common_certs_import = 1; break;
1345 case oEnableSpecialFilenames: allow_special_filenames =1; break;
1347 case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
1349 case oKeyServer:
1351 struct keyserver_spec *keyserver;
1352 keyserver = parse_keyserver_line (pargs.r.ret_str,
1353 configname, configlineno);
1354 if (! keyserver)
1355 log_error (_("could not parse keyserver\n"));
1356 else
1358 /* FIXME: Keep last next pointer. */
1359 struct keyserver_spec **next_p = &opt.keyserver;
1360 while (*next_p)
1361 next_p = &(*next_p)->next;
1362 *next_p = keyserver;
1365 break;
1367 default:
1368 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
1369 break;
1373 if (configfp)
1375 fclose (configfp);
1376 configfp = NULL;
1377 /* Keep a copy of the config filename. */
1378 opt.config_filename = configname;
1379 configname = NULL;
1380 goto next_pass;
1382 xfree (configname);
1383 configname = NULL;
1385 if (!opt.config_filename)
1386 opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
1388 if (log_get_errorcount(0))
1389 gpgsm_exit(2);
1391 /* Now that we have the options parsed we need to update the default
1392 control structure. */
1393 gpgsm_init_default_ctrl (&ctrl);
1395 if (nogreeting)
1396 greeting = 0;
1398 if (greeting)
1400 fprintf(stderr, "%s %s; %s\n",
1401 strusage(11), strusage(13), strusage(14) );
1402 fprintf(stderr, "%s\n", strusage(15) );
1404 # ifdef IS_DEVELOPMENT_VERSION
1405 if (!opt.batch)
1407 log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
1408 log_info ("It is only intended for test purposes and should NOT be\n");
1409 log_info ("used in a production environment or with production keys!\n");
1411 # endif
1413 if (auditlog)
1414 log_info ("NOTE: The audit log feature (--audit-log) is "
1415 "WORK IN PRORESS and not ready for use!\n");
1418 if (may_coredump && !opt.quiet)
1419 log_info (_("WARNING: program may create a core file!\n"));
1421 /* if (opt.qualsig_approval && !opt.quiet) */
1422 /* log_info (_("This software has offically been approved to " */
1423 /* "create and verify\n" */
1424 /* "qualified signatures according to German law.\n")); */
1426 if (logfile && cmd == aServer)
1428 log_set_file (logfile);
1429 log_set_prefix (NULL, 1|2|4);
1432 if (gnupg_faked_time_p ())
1434 gnupg_isotime_t tbuf;
1436 log_info (_("WARNING: running with faked system time: "));
1437 gnupg_get_isotime (tbuf);
1438 dump_isotime (tbuf);
1439 log_printf ("\n");
1442 /*FIXME if (opt.batch) */
1443 /* tty_batchmode (1); */
1445 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
1447 set_debug ();
1449 /* Although we alwasy use gpgsm_exit, we better install a regualr
1450 exit handler so that at least the secure memory gets wiped
1451 out. */
1452 if (atexit (emergency_cleanup))
1454 log_error ("atexit failed\n");
1455 gpgsm_exit (2);
1458 /* Must do this after dropping setuid, because the mapping functions
1459 may try to load an module and we may have disabled an algorithm.
1460 We remap the commonly used algorithms to the OIDs for
1461 convenience. We need to work with the OIDs because they are used
1462 to check whether the encryption mode is actually available. */
1463 if (!strcmp (opt.def_cipher_algoid, "3DES") )
1464 opt.def_cipher_algoid = "1.2.840.113549.3.7";
1465 else if (!strcmp (opt.def_cipher_algoid, "AES")
1466 || !strcmp (opt.def_cipher_algoid, "AES128"))
1467 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
1468 else if (!strcmp (opt.def_cipher_algoid, "AES256") )
1469 opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
1470 else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
1471 || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
1472 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
1473 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1474 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
1475 else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
1476 opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
1477 else if (!strcmp (opt.def_cipher_algoid, "SEED") )
1478 opt.def_cipher_algoid = "1.2.410.200004.1.4";
1479 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
1480 || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
1481 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
1482 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
1483 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
1484 else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
1485 opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
1487 if (cmd != aGPGConfList)
1489 if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
1490 || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
1491 log_error (_("selected cipher algorithm is invalid\n"));
1493 if (forced_digest_algo)
1495 opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
1496 if (our_md_test_algo(opt.forced_digest_algo) )
1497 log_error (_("selected digest algorithm is invalid\n"));
1499 if (extra_digest_algo)
1501 opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
1502 if (our_md_test_algo (opt.extra_digest_algo) )
1503 log_error (_("selected digest algorithm is invalid\n"));
1507 if (log_get_errorcount(0))
1508 gpgsm_exit(2);
1510 /* Set the random seed file. */
1511 if (use_random_seed)
1513 char *p = make_filename (opt.homedir, "random_seed", NULL);
1514 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
1515 xfree(p);
1518 if (!cmd && opt.fingerprint && !with_fpr)
1519 set_cmd (&cmd, aListKeys);
1521 /* Add default keybox. */
1522 if (!nrings && default_keyring)
1524 int created;
1526 keydb_add_resource ("pubring.kbx", 0, 0, &created);
1527 if (created && !no_common_certs_import)
1529 /* Import the standard certificates for a new default keybox. */
1530 char *filelist[2];
1532 filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
1533 filelist[1] = NULL;
1534 if (!access (filelist[0], F_OK))
1536 log_info (_("importing common certificates `%s'\n"),
1537 filelist[0]);
1538 gpgsm_import_files (&ctrl, 1, filelist, open_read);
1540 xfree (filelist[0]);
1543 for (sl = nrings; sl; sl = sl->next)
1544 keydb_add_resource (sl->d, 0, 0, NULL);
1545 FREE_STRLIST(nrings);
1548 /* Prepare the audit log feature for certain commands. */
1549 if (auditlog)
1551 switch (cmd)
1553 case aEncr:
1554 case aSign:
1555 case aDecrypt:
1556 case aVerify:
1557 audit_release (ctrl.audit);
1558 ctrl.audit = audit_new ();
1559 auditfp = open_es_fwrite (auditlog);
1560 break;
1561 default:
1562 break;
1567 if (!do_not_setup_keys)
1569 for (sl = locusr; sl ; sl = sl->next)
1571 int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
1572 if (rc)
1574 log_error (_("can't sign using `%s': %s\n"),
1575 sl->d, gpg_strerror (rc));
1576 gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
1577 get_inv_recpsgnr_code (rc), sl->d, NULL);
1578 gpgsm_status2 (&ctrl, STATUS_INV_RECP,
1579 get_inv_recpsgnr_code (rc), sl->d, NULL);
1583 /* Build the recipient list. We first add the regular ones and then
1584 the encrypt-to ones because the underlying function will silently
1585 ignore duplicates and we can't allow to keep a duplicate which is
1586 flagged as encrypt-to as the actually encrypt function would then
1587 complain about no (regular) recipients. */
1588 for (sl = remusr; sl; sl = sl->next)
1589 if (!(sl->flags & 1))
1590 do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
1591 if (!opt.no_encrypt_to)
1593 for (sl = remusr; sl; sl = sl->next)
1594 if ((sl->flags & 1))
1595 do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
1599 if (log_get_errorcount(0))
1600 gpgsm_exit(1); /* Must stop for invalid recipients. */
1602 fname = argc? *argv : NULL;
1604 /* Dispatch command. */
1605 switch (cmd)
1607 case aGPGConfList:
1608 { /* List options and default values in the GPG Conf format. */
1609 char *config_filename_esc = percent_escape (opt.config_filename, NULL);
1611 printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
1612 GC_OPT_FLAG_DEFAULT, config_filename_esc);
1613 xfree (config_filename_esc);
1615 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1616 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1617 printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1618 printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1619 printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
1620 printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
1621 printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
1622 printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1623 DEFAULT_INCLUDE_CERTS);
1624 printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
1625 printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1626 printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1627 #ifndef HAVE_W32_SYSTEM
1628 printf ("prefer-system-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1629 #endif
1630 printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1631 DEFAULT_CIPHER_ALGO);
1632 printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
1633 printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
1634 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
1635 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1638 break;
1639 case aGPGConfTest:
1640 /* This is merely a dummy command to test whether the
1641 configuration file is valid. */
1642 break;
1644 case aServer:
1645 if (debug_wait)
1647 log_debug ("waiting for debugger - my pid is %u .....\n",
1648 (unsigned int)getpid());
1649 gnupg_sleep (debug_wait);
1650 log_debug ("... okay\n");
1652 gpgsm_server (recplist);
1653 break;
1655 case aCallDirmngr:
1656 if (!argc)
1657 wrong_args ("--call-dirmngr <command> {args}");
1658 else
1659 if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
1660 gpgsm_exit (1);
1661 break;
1663 case aCallProtectTool:
1664 run_protect_tool (argc, argv);
1665 break;
1667 case aEncr: /* Encrypt the given file. */
1669 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1671 set_binary (stdin);
1673 if (!argc) /* Source is stdin. */
1674 gpgsm_encrypt (&ctrl, recplist, 0, fp);
1675 else if (argc == 1) /* Source is the given file. */
1676 gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
1677 else
1678 wrong_args ("--encrypt [datafile]");
1680 if (fp != stdout)
1681 fclose (fp);
1683 break;
1685 case aSign: /* Sign the given file. */
1687 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1689 /* Fixme: We should also allow to concatenate multiple files for
1690 signing because that is what gpg does.*/
1691 set_binary (stdin);
1692 if (!argc) /* Create from stdin. */
1693 gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
1694 else if (argc == 1) /* From file. */
1695 gpgsm_sign (&ctrl, signerlist,
1696 open_read (*argv), detached_sig, fp);
1697 else
1698 wrong_args ("--sign [datafile]");
1700 if (fp != stdout)
1701 fclose (fp);
1703 break;
1705 case aSignEncr: /* sign and encrypt the given file */
1706 log_error ("this command has not yet been implemented\n");
1707 break;
1709 case aClearsign: /* make a clearsig */
1710 log_error ("this command has not yet been implemented\n");
1711 break;
1713 case aVerify:
1715 FILE *fp = NULL;
1717 set_binary (stdin);
1718 if (argc == 2 && opt.outfile)
1719 log_info ("option --output ignored for a detached signature\n");
1720 else if (opt.outfile)
1721 fp = open_fwrite (opt.outfile);
1723 if (!argc)
1724 gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
1725 else if (argc == 1)
1726 gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
1727 else if (argc == 2) /* detached signature (sig, detached) */
1728 gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
1729 else
1730 wrong_args ("--verify [signature [detached_data]]");
1732 if (fp && fp != stdout)
1733 fclose (fp);
1735 break;
1737 case aDecrypt:
1739 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1741 set_binary (stdin);
1742 if (!argc)
1743 gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
1744 else if (argc == 1)
1745 gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
1746 else
1747 wrong_args ("--decrypt [filename]");
1748 if (fp != stdout)
1749 fclose (fp);
1751 break;
1753 case aDeleteKey:
1754 for (sl=NULL; argc; argc--, argv++)
1755 add_to_strlist (&sl, *argv);
1756 gpgsm_delete (&ctrl, sl);
1757 free_strlist(sl);
1758 break;
1760 case aListChain:
1761 case aDumpChain:
1762 ctrl.with_chain = 1;
1763 case aListKeys:
1764 case aDumpKeys:
1765 case aListExternalKeys:
1766 case aDumpExternalKeys:
1767 case aListSecretKeys:
1768 case aDumpSecretKeys:
1770 unsigned int mode;
1771 estream_t fp;
1773 switch (cmd)
1775 case aListChain:
1776 case aListKeys: mode = (0 | 0 | (1<<6)); break;
1777 case aDumpChain:
1778 case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
1779 case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
1780 case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
1781 case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
1782 case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
1783 default: BUG();
1786 fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
1787 for (sl=NULL; argc; argc--, argv++)
1788 add_to_strlist (&sl, *argv);
1789 gpgsm_list_keys (&ctrl, sl, fp, mode);
1790 free_strlist(sl);
1791 es_fclose (fp);
1793 break;
1796 case aKeygen: /* Generate a key; well kind of. */
1798 estream_t fpin = NULL;
1799 FILE *fpout;
1801 if (opt.batch)
1803 if (!argc) /* Create from stdin. */
1804 fpin = open_es_fread ("-");
1805 else if (argc == 1) /* From file. */
1806 fpin = open_es_fread (*argv);
1807 else
1808 wrong_args ("--gen-key --batch [parmfile]");
1811 fpout = open_fwrite (opt.outfile?opt.outfile:"-");
1813 if (fpin)
1814 gpgsm_genkey (&ctrl, fpin, fpout);
1815 else
1816 gpgsm_gencertreq_tty (&ctrl, fpout);
1818 if (fpout != stdout)
1819 fclose (fpout);
1821 break;
1824 case aImport:
1825 gpgsm_import_files (&ctrl, argc, argv, open_read);
1826 break;
1828 case aExport:
1830 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1832 for (sl=NULL; argc; argc--, argv++)
1833 add_to_strlist (&sl, *argv);
1834 gpgsm_export (&ctrl, sl, fp, NULL);
1835 free_strlist(sl);
1836 if (fp != stdout)
1837 fclose (fp);
1839 break;
1841 case aExportSecretKeyP12:
1843 FILE *fp = open_fwrite (opt.outfile?opt.outfile:"-");
1845 if (argc == 1)
1846 gpgsm_p12_export (&ctrl, *argv, fp);
1847 else
1848 wrong_args ("--export-secret-key-p12 KEY-ID");
1849 if (fp != stdout)
1850 fclose (fp);
1852 break;
1854 case aSendKeys:
1855 case aRecvKeys:
1856 log_error ("this command has not yet been implemented\n");
1857 break;
1860 case aLearnCard:
1861 if (argc)
1862 wrong_args ("--learn-card");
1863 else
1865 int rc = gpgsm_agent_learn (&ctrl);
1866 if (rc)
1867 log_error ("error learning card: %s\n", gpg_strerror (rc));
1869 break;
1871 case aPasswd:
1872 if (argc != 1)
1873 wrong_args ("--passwd <key-Id>");
1874 else
1876 int rc;
1877 ksba_cert_t cert = NULL;
1878 char *grip = NULL;
1880 rc = gpgsm_find_cert (*argv, NULL, &cert);
1881 if (rc)
1883 else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
1884 rc = gpg_error (GPG_ERR_BUG);
1885 else
1887 char *desc = gpgsm_format_keydesc (cert);
1888 rc = gpgsm_agent_passwd (&ctrl, grip, desc);
1889 xfree (desc);
1891 if (rc)
1892 log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
1893 xfree (grip);
1894 ksba_cert_release (cert);
1896 break;
1898 case aKeydbClearSomeCertFlags:
1899 for (sl=NULL; argc; argc--, argv++)
1900 add_to_strlist (&sl, *argv);
1901 keydb_clear_some_cert_flags (&ctrl, sl);
1902 free_strlist(sl);
1903 break;
1906 default:
1907 log_error (_("invalid command (there is no implicit command)\n"));
1908 break;
1911 /* Print the audit result if needed. */
1912 if (auditlog && auditfp)
1914 audit_print_result (ctrl.audit, auditfp, 0);
1915 audit_release (ctrl.audit);
1916 ctrl.audit = NULL;
1917 es_fclose (auditfp);
1920 /* cleanup */
1921 keyserver_list_free (opt.keyserver);
1922 opt.keyserver = NULL;
1923 gpgsm_release_certlist (recplist);
1924 gpgsm_release_certlist (signerlist);
1925 FREE_STRLIST (remusr);
1926 FREE_STRLIST (locusr);
1927 gpgsm_exit(0);
1928 return 8; /*NOTREACHED*/
1931 /* Note: This function is used by signal handlers!. */
1932 static void
1933 emergency_cleanup (void)
1935 gcry_control (GCRYCTL_TERM_SECMEM );
1939 void
1940 gpgsm_exit (int rc)
1942 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
1943 if (opt.debug & DBG_MEMSTAT_VALUE)
1945 gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
1946 gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
1948 if (opt.debug)
1949 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
1950 emergency_cleanup ();
1951 rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
1952 exit (rc);
1956 void
1957 gpgsm_init_default_ctrl (struct server_control_s *ctrl)
1959 ctrl->include_certs = default_include_certs;
1960 ctrl->use_ocsp = opt.enable_ocsp;
1961 ctrl->validation_model = default_validation_model;
1966 gpgsm_parse_validation_model (const char *model)
1968 if (!ascii_strcasecmp (model, "shell") )
1969 return 0;
1970 else if ( !ascii_strcasecmp (model, "chain") )
1971 return 1;
1972 else
1973 return -1;
1977 /* Check whether the filename has the form "-&nnnn", where n is a
1978 non-zero number. Returns this number or -1 if it is not the case. */
1979 static int
1980 check_special_filename (const char *fname, int for_write)
1982 if (allow_special_filenames
1983 && fname && *fname == '-' && fname[1] == '&' ) {
1984 int i;
1986 fname += 2;
1987 for (i=0; isdigit (fname[i]); i++ )
1989 if ( !fname[i] )
1990 return translate_sys2libc_fd_int (atoi (fname), for_write);
1992 return -1;
1997 /* Open the FILENAME for read and return the filedescriptor. Stop
1998 with an error message in case of problems. "-" denotes stdin and
1999 if special filenames are allowed the given fd is opened instead. */
2000 static int
2001 open_read (const char *filename)
2003 int fd;
2005 if (filename[0] == '-' && !filename[1])
2007 set_binary (stdin);
2008 return 0; /* stdin */
2010 fd = check_special_filename (filename, 0);
2011 if (fd != -1)
2012 return fd;
2013 fd = open (filename, O_RDONLY | O_BINARY);
2014 if (fd == -1)
2016 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2017 gpgsm_exit (2);
2019 return fd;
2022 /* Same as open_read but return an estream_t. */
2023 static estream_t
2024 open_es_fread (const char *filename)
2026 int fd;
2027 estream_t fp;
2029 if (filename[0] == '-' && !filename[1])
2030 fd = fileno (stdin);
2031 else
2032 fd = check_special_filename (filename, 0);
2033 if (fd != -1)
2035 fp = es_fdopen_nc (fd, "rb");
2036 if (!fp)
2038 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2039 gpgsm_exit (2);
2041 return fp;
2043 fp = es_fopen (filename, "rb");
2044 if (!fp)
2046 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2047 gpgsm_exit (2);
2049 return fp;
2053 /* Open FILENAME for fwrite and return the stream. Stop with an error
2054 message in case of problems. "-" denotes stdout and if special
2055 filenames are allowed the given fd is opened instead. Caller must
2056 close the returned stream unless it is stdout. */
2057 static FILE *
2058 open_fwrite (const char *filename)
2060 int fd;
2061 FILE *fp;
2063 if (filename[0] == '-' && !filename[1])
2065 set_binary (stdout);
2066 return stdout;
2069 fd = check_special_filename (filename, 1);
2070 if (fd != -1)
2072 fp = fdopen (dup (fd), "wb");
2073 if (!fp)
2075 log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
2076 gpgsm_exit (2);
2078 set_binary (fp);
2079 return fp;
2081 fp = fopen (filename, "wb");
2082 if (!fp)
2084 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2085 gpgsm_exit (2);
2087 return fp;
2091 /* Open FILENAME for fwrite and return an extended stream. Stop with
2092 an error message in case of problems. "-" denotes stdout and if
2093 special filenames are allowed the given fd is opened instead.
2094 Caller must close the returned stream. */
2095 static estream_t
2096 open_es_fwrite (const char *filename)
2098 int fd;
2099 estream_t fp;
2101 if (filename[0] == '-' && !filename[1])
2103 fflush (stdout);
2104 fp = es_fdopen_nc (fileno(stdout), "wb");
2105 return fp;
2108 fd = check_special_filename (filename, 1);
2109 if (fd != -1)
2111 fp = es_fdopen_nc (fd, "wb");
2112 if (!fp)
2114 log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
2115 gpgsm_exit (2);
2117 return fp;
2119 fp = es_fopen (filename, "wb");
2120 if (!fp)
2122 log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
2123 gpgsm_exit (2);
2125 return fp;
2129 static void
2130 run_protect_tool (int argc, char **argv)
2132 #ifndef HAVE_W32_SYSTEM
2133 const char *pgm;
2134 char **av;
2135 int i;
2137 if (!opt.protect_tool_program || !*opt.protect_tool_program)
2138 pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
2139 else
2140 pgm = opt.protect_tool_program;
2142 av = xcalloc (argc+2, sizeof *av);
2143 av[0] = strrchr (pgm, '/');
2144 if (!av[0])
2145 av[0] = xstrdup (pgm);
2146 for (i=1; argc; i++, argc--, argv++)
2147 av[i] = *argv;
2148 av[i] = NULL;
2149 execv (pgm, av);
2150 log_error ("error executing `%s': %s\n", pgm, strerror (errno));
2151 #endif /*HAVE_W32_SYSTEM*/
2152 gpgsm_exit (2);